加载谷歌地图绘图管理器对象

时间:2012-09-06 15:01:45

标签: google-maps google-maps-api-3

所以我使用谷歌地图绘图管理器绘制一些多边形,我将lat长坐标保存到我的数据库。现在我的问题是,在我将其加载到我的数组后,如何将保存的多边形重建回我的地图?我似乎无法找到理解这一点的代码。

这就是我现在所拥有的:

    window.initialize_2 = function () {
    var mapOptions = {
        center: new google.maps.LatLng(-34.397, 150.644),
        zoom: 8,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    var map = maplimits;

    var drawingManager = new google.maps.drawing.DrawingManager({
        drawingMode: google.maps.drawing.OverlayType.MARKER,
        drawingControl: true,
        drawingControlOptions: {
            position: google.maps.ControlPosition.TOP_CENTER,
            drawingModes: [
            google.maps.drawing.OverlayType.POLYGON]
        },
        markerOptions: {
            icon: 'images/beachflag.png'
        },
        polygonOptions: {
            fillColor: '#ffff00',
            fillOpacity: 10,
            strokeWeight: 5,
            clickable: true,
            editable: true,
            zIndex: 1
        }
 });

    var coord_listener = google.maps.event.addListener(drawingManager, 'polygoncomplete', function (polygon) {
        var coordinates = (polygon.getPath().getArray());
        console.log(coordinates);
        window.poly = polygon;
    });

    //delete shape
    google.maps.event.addListener(drawingManager, 'overlaycomplete', function (e) {
        if (e.type != google.maps.drawing.OverlayType.MARKER) {
            // Switch back to non-drawing mode after drawing a shape.
            drawingManager.setDrawingMode(null);

            // Add an event listener that selects the newly-drawn shape when the user
            // mouses down on it.
            var newShape = e.overlay;
            newShape.type = e.type;
            google.maps.event.addListener(newShape, 'click', function () {
                setSelection(newShape);
            });
            setSelection(newShape);
        }
    });

    // Clear the current selection when the drawing mode is changed, or when the
    // map is clicked.
    google.maps.event.addListener(drawingManager, 'drawingmode_changed', clearSelection);
    google.maps.event.addListener(map, 'click', clearSelection);

    drawingManager.setMap(map);
}

2 个答案:

答案 0 :(得分:1)

因此多边形应该保留在地图上。我猜你的意思是稍后在地图的另一个实例中你想根据先前的输入绘制多边形?在这种情况下,您将创建一个Polygon Overlay。在我刚刚链接的文档中,它非常简单。

答案 1 :(得分:1)

设置一个全局数组(它更容易),并在侦听器中将多边形存储在其上,然后创建一个函数将其设置为地图。

这样的事情:

var polygons = [];

window.initialize_2 = function () {
var mapOptions = {
...
var coord_listener = google.maps.event.addListener(drawingManager, 'polygoncomplete', function (polygon) {
        var coordinates = (polygon.getPath().getArray());
        console.log(coordinates);
        window.poly = polygon;
        poligons = [] // clear the array
        polygons.push(polygon); // insert the polygon into the array
    });
...
    drawingManager.setMap(map);
}

function setPolygon(){
  polygons[0].setMap(map) // set the polygon to the map
}

希望它对你有所帮助。 问候。