Using Baidu map to realize map grid

Posted by nomad9 on Wed, 15 Apr 2020 20:10:36 +0200

Recently, baidu map will be used to realize the function of building visualization, so the most basic function is to realize the division of building in different regions after gridding the map;

1. Go to the open platform of Baidu map to apply for the secret key. Here I post my secret key; ak=A3CklGvnFOjkAzKzay2dySgfdig0GKz4

2. Create a new simple page. Next, I will post my own page

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <style type="text/css">
        html {
            height: 100%
        }

        body {
            height: 100%;
            margin: 0px;
            padding: 0px
        }

        #container {
            height: 100%
        }
    </style>
    <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=A3CklGvnFOjkAzKzay2dySgfdig0GKz4"></script> 
<script type="text/javascript" src="ziroom-map.js"></script>
 </head>
 <body> 
<div id="container"></div>
 <script> 
var myMap = new ZMap("container"); </script>
 </body>
 </html>

3. ziroom-map.js is introduced. This is the name of our company. I post the code. This JS encapsulates Baidu's JS api. If someone wants to ask why it is encapsulated, can't it be directly used? Then my answer is: encapsulation can combine the specific business with the map, make the code clearer, and can persist the current map state, which is conducive to the operation of the map.

var ZMap = function (id, center, level) {
    this.initCenter = new ZPoint(116.404, 39.915);//Initializes the center point of the mesh in order to define the center point of the mesh
    this.id = id;//div Of id
    this.level = level ? level : 13;//Map level
    this.center = center ? center : this.initCenter;//Center point

    this.map = null;//Baidu map example
    this.xgrids = [];//Warp
    this.ygrids = [];//Weft line
    this.beSelectBounds = {};
    this.bounds = null;//Four vertices of the current map
    this.span = null;//The span of the current grid

    this.init();

}
ZMap.prototype = {
    init: function () {//Global initialization
        var zMap = this;
        this.map = new BMap.Map(this.id);
        this.map.centerAndZoom(this.center.point, this.level);
        this.map.enableScrollWheelZoom();
        this.map.disableInertialDragging();
        this.map.addControl(new BMap.NavigationControl({
            anchor: BMAP_ANCHOR_BOTTOM_RIGHT,
            type: BMAP_NAVIGATION_CONTROL_ZOOM
        })); //Zoom button
        this.map.addControl(new BMap.ScaleControl({anchor: BMAP_ANCHOR_BOTTOM_LEFT, offset: new BMap.Size(80, 25)})); //scale
        this.map.disableDoubleClickZoom();
        this.map.setMapStyle({style: 'googlelite'});
        this.initProperty();
        this.initGrid();

        //Add mobile click event
        this.map.addEventListener("dragend", function () {
            zMap.initProperty();
            zMap.initGrid();
        });
        //Add events that zoom in or out
        this.map.addEventListener("zoomend", function () {
            zMap.initProperty();
            zMap.initGrid();
        });
        //Set click event
        this.map.addEventListener("click", function (e) {
            var point = e.point;
            //Get which block the current point is in,Get four vertices of a square
            var points = zMap.getGrid(point);

            //Determine whether the current area has been selected. If it has been selected, uncheck it
            var key = '' + points[0].lng + points[0].lat + points[2].lng + points[2].lat;//Use the coordinates of two points as key
            if (zMap.beSelectBounds[key]) {
                zMap.map.removeOverlay(zMap.beSelectBounds[key]);
                delete zMap.beSelectBounds[key];
                return;
            }
            var polygon = new BMap.Polygon(points, {strokeColor: "red", strokeWeight: 2, strokeOpacity: 0.5});
            zMap.map.addOverlay(polygon);
            zMap.beSelectBounds[key] = polygon;

        });
    },
    initProperty: function () {//Initialize the status of the current map
        this.level = this.map.getZoom();
        this.bounds = {
            x1: this.map.getBounds().getSouthWest().lng,
            y1: this.map.getBounds().getSouthWest().lat,
            x2: this.map.getBounds().getNorthEast().lng,
            y2: this.map.getBounds().getNorthEast().lat
        };
        this.span = this.getSpan();//Need to use level attribute
    },
    initGrid: function () {//Initialize grid
        var zMap = this;
        //Remove the original gridlines first
        for (var i in zMap.xgrids) {
            this.map.removeOverlay(zMap.xgrids[i]);
        }
        zMap.xgrids = [];
        for (var i in zMap.ygrids) {
            this.map.removeOverlay(zMap.ygrids[i]);
        }
        zMap.ygrids = [];
        //Get current grid span
        var span = zMap.span;
        //Initialize grid on map
        for (var i = zMap.bounds.x1 + (zMap.initCenter.point.lng - zMap.bounds.x1) % span.x - span.x; i < zMap.bounds.x2 + span.x; i += span.x) {
            var polyline = new BMap.Polyline([
                new BMap.Point(i.toFixed(6), zMap.bounds.y1),
                new BMap.Point(i.toFixed(6), zMap.bounds.y2)
            ], {strokeColor: "black", strokeWeight: 1, strokeOpacity: 0.5});
            zMap.xgrids.push(polyline);
            zMap.map.addOverlay(polyline);
        }
        for (var i = zMap.bounds.y1 + (zMap.initCenter.point.lat - zMap.bounds.y1) % span.y - span.y; i < zMap.bounds.y2 + span.y; i += span.y) {
            var polyline = new BMap.Polyline([
                new BMap.Point(zMap.bounds.x1, i.toFixed(6)),
                new BMap.Point(zMap.bounds.x2, i.toFixed(6))
            ], {strokeColor: "black", strokeWeight: 1, strokeOpacity: 0.5});
            zMap.ygrids.push(polyline);
            zMap.map.addOverlay(polyline);
        }
    },
    getSpan: function () {//Get the span of the grid
        var scale = 0.75;
        var x = 0.00064;
        for (var i = this.level; i < 19; i++) {
            x *= 2;
        }
        var y = parseFloat((scale * x).toFixed(5));
        return {x: x, y: y};
    },
    getGrid: function (point) {//Returns the four vertices of the current point in the block
        var zMap = this;
        //First find out the coordinates of two vertical lines
        var xpoints = this.xgrids.map(function (polyline) {
            return polyline.getPath()[0].lng;
        }).filter(function (lng) {
            return Math.abs(lng - point.lng) <= zMap.span.x;
        }).sort(function (a, b) {
            return a - b;
        }).slice(0, 2);

        //Find out the coordinates of two more horizontal lines
        var ypoints = this.ygrids.map(function (polyline) {
            return polyline.getPath()[0].lat;
        }).filter(function (lat) {
            return Math.abs(lat - point.lat) <= zMap.span.y;
        }).sort(function (a, b) {
            return a - b;
        }).slice(0, 2);

        return [
            new BMap.Point(xpoints[0], ypoints[0]),
            new BMap.Point(xpoints[0], ypoints[1]),
            new BMap.Point(xpoints[1], ypoints[1]),
            new BMap.Point(xpoints[1], ypoints[0])
        ];

    },
    reset: function () {//Reset
        this.map.reset();
    }
}

var ZPoint = function (x, y, code) {
    this.code = code;
    this.point = new BMap.Point(x, y);
}

Summary: Well, there are so many essays. Welcome to correct them.

Topics: Javascript Mobile Attribute