Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I capture point locations of Polygon with Google Maps API?

Using the Google Maps API Drawing Manager, I want to collect the location of each point in the polygon that is drawn by a user.

I know there is a getPath() function, but I'm not sure where I use it.

This is all the code I have so far:

var map; var drawingManager;

function initialize() {
    var mapOptions = {
        center: new google.maps.LatLng(45.13536, -100.762952),
        zoom: 14,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

    drawingManager = new google.maps.drawing.DrawingManager({
        drawingMode: google.maps.drawing.OverlayType.POLYGON,
        drawingControl: false,
        polygonOptions: {
            fillColor: "#000000",
            fillOpacity: .6,
            strokeWeight: 1,
            strokeColor: "#666666",
            clickable: false,
            editable: true,
            zIndex: 1
        }
    });

    drawingManager.setMap(map);

    google.maps.event.addListener(drawingManager, 'polygoncomplete', function(polygon) {
        drawingManager.setDrawingMode(null);
    });
}

google.maps.event.addDomListener(window, 'load', initialize);

So from this code, how can I use the getPath() function to show the coordinates that make up the Polygon that is drawn?

like image 644
ianbroad Avatar asked Sep 24 '13 01:09

ianbroad


Video Answer


1 Answers

use it inside the polygoncomplete-callback.

example:

 google.maps.event.addListener(drawingManager, 'polygoncomplete', function(polygon) {
    drawingManager.setDrawingMode(null);
    var arr=[];
    polygon.getPath().forEach(function(latLng){arr.push(latLng.toString());})
    alert(arr.join(',\n'));
});

it iterates over the path(using the forEach-method of a google.maps.MVCArray) and populates another array with the string-representations of the LatLng's

like image 137
Dr.Molle Avatar answered Sep 27 '22 23:09

Dr.Molle