Mehran Hafizi
Mehran Hafizi

Reputation: 2592

How to programmatically draw a polygon with google map DrawManager

I'm using the google map to define the areas of a city. A user draws a polygon to determine a desired area. To reach this objective, I am referring to DrawingManager article this article. Everything goes well unit I want to update the registered area and draw the polygon. The path I would like to follow is using DrawingManager. This is my code. The code loads the map correctly ,but it does not draw my polygon based on give coordinates.

GoogleMap.prototype.initial = function (currentPolygonData) {
var self = this;
var triangleCoords = [];
if (currentPolygonData != null && currentPolygonData.length>0) {
    triangleCoords = [];
    for (var i = 0; i < currentPolygonData.length; i++) {
        triangleCoords.push(new google.maps.LatLng(currentPolygonData[i].Lat, currentPolygonData[i].Lng));
    }
}
var polyOptions = {
    paths: triangleCoords,
    strokeColor: '#bb4446',
    fillColor: '#c37172',
    strokeWeight: 0,
    fillOpacity: 0.45,
    editable: true,
    draggable: true,
};

self.drawingManager = new google.maps.drawing.DrawingManager({
    drawingMode: google.maps.drawing.OverlayType.POLYGON,
    drawingControlOptions: {
        drawingModes: [
            google.maps.drawing.OverlayType.POLYGON
        ]
    },
    markerOptions: {
        draggable: true

    },
    polylineOptions: {
        editable: true,
        draggable: true

    },
    rectangleOptions: polyOptions,
    circleOptions: polyOptions,
    polygonOptions: polyOptions,
    map: self.map
});}

Upvotes: 3

Views: 2179

Answers (1)

Aishwary Dhare
Aishwary Dhare

Reputation: 539

The datatype for a collection of LatLng should be an array of dictionary with keys as 'lat' and 'lng' for latitude and longitude respectively.

Hence in your code it should be

var triangleCoordsArr = {};
if (currentPolygonData != null && currentPolygonData.length>0) {
    for (var i = 0; i < currentPolygonData.length; i++) {
        triangleCoords = {};
        triangleCoords['lat'] = currentPolygonData[i].Lat;
        triangleCoords['lng'] = currentPolygonData[i].Lng;
        triangleCoordsArr.push(triangleCoords)
    }
}    
for (var i = 0; i < triangleCoordsArr.length; i++) {
    // Construct the polygon.
    var mTriangle = new google.maps.Polygon({
        paths: triangleCoordsArr[i],
        strokeColor: '#FF0000',
        strokeOpacity: 0.8,
        strokeWeight: 2,
        fillColor: '#FF0000',
        fillOpacity: 0.35
    });
    mTriangle.setMap(map);
}

Also, here this reference link from Maps Documentation should be helpful for more info to solve your case

Upvotes: 1

Related Questions