1. 程式人生 > >百度地圖中動態生成網格

百度地圖中動態生成網格

目的:根據距離生成網格,比如500米一個網格

技術:js 百度地圖

程式碼如此下:

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <style type="text/css">
        body, html{width: 100%;height: 100%;margin:0;font-family:"微軟雅黑";}
        #allmap {height:500px; width: 100%;}
        #control{width:100%;}
    </style>
    <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=A8670c09c603b2e409efef4709e83f0c"></script>
    <title>設定線</title>
</head>
<body>
    <div id="allmap"></div>

</body>
</html>
<script type="text/javascript">
    // 百度地圖API功能

    var wsmap = {
        map: null,
        XY: null,

        mapLoad: function () {
            this.map = new BMap.Map("allmap");
            this.map.centerAndZoom(new BMap.Point(116.404, 39.915), 15);
            var bottom_right_navigation = new BMap.NavigationControl({ anchor: BMAP_ANCHOR_BOTTOM_RIGHT, type: BMAP_NAVIGATION_CONTROL_ZOOM }); //縮放按鈕
            var bottom_left_control = new BMap.ScaleControl({ anchor: BMAP_ANCHOR_BOTTOM_LEFT, offset: new BMap.Size(0, 30) }); //比例尺
            this.map.addControl(bottom_left_control);
            this.map.addControl(bottom_right_navigation);    //新增地圖型別控制元件

            this.map.enableScrollWheelZoom();
            this.showPolyline();
            this.map.addEventListener("dragend", function () { wsmap.showPolyline(); });
            this.map.addEventListener("zoomend", function () { wsmap.showPolyline(); });
        },
        bs: function () {
            var bs = this.map.getBounds();
            var bssw = bs.getSouthWest();
            var bsne = bs.getNorthEast();
            return { 'x1': bssw.lng, 'y1': bssw.lat, 'x2': bsne.lng, 'y2': bsne.lat };
        },
        showPolyline: function () {
            var zoome = this.map.getZoom();

            this.map.clearOverlays();
            if (zoome > 12) {
                this.XY = this.bs();

                for (var i = this.XY.x1; i < this.XY.x2; i = i + 0.0063) {
                    var polyline = new BMap.Polyline([
                        new BMap.Point(i, this.XY.y1),
                        new BMap.Point(i, this.XY.y2),
                    ], { strokeColor: "black", strokeWeight: 1, strokeOpacity: 0.5 });
                    this.map.addOverlay(polyline);
                }

                for (var i = this.XY.y1; i < this.XY.y2; i = i + 0.0048) {
                    var polyline = new BMap.Polyline([
                        new BMap.Point(this.XY.x1, i),
                        new BMap.Point(this.XY.x2, i),
                     ], { strokeColor: "black", strokeWeight: 1, strokeOpacity: 0.5 });
                    this.map.addOverlay(polyline);
                }
            }

        }

    }
    wsmap.mapLoad();
</script>