Drawing a Polygon with Google Maps

danswill
danswill used Ask the Experts™
on
Hello Experts!

I’m trying to allow a user to draw a polygon on a Google Map and once it’s drawn, I would like to get the coordinates.

First question – In Google Maps Javascript v3, how can I allow the user to draw a polygon (I've already done this, but there may be a better approach, code sample below) and then get the coordinates from the user?

Second question – When the user drags the polygon vertices, how can I get the new coordinates of the polygon?

Here’s my code so far:

var mapOptions = {
            center: { lat: 39.7683333, lng: -86.1580556},
            zoom: 10
        };

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


        var polyOptions = {
            strokeColor: '#000000',
            strokeOpacity: 1.0,
            strokeWeight: 3,
            editable:true,
            fillOpacity:.1,
            fillColor:'#333333'
        };
        poly = new google.maps.Polygon(polyOptions);
        poly.setMap(map);

        // Add a listener for the click event
        google.maps.event.addListener(map, 'click', this.addLatLng);


        google.maps.event.addListener(poly, 'set_at', getPolygonCoords );
        google.maps.event.addListener(poly, 'insert_at',getPolygonCoords);
        google.maps.event.addListener(poly, 'remove_at',getPolygonCoords);

function getPolygonCoords(event){
    var vertices = this.getPath();
    for (var i =0; i < vertices.getLength(); i++) {
        var xy = vertices.getAt(i);
        
        console.log(xy.lat()+" "+xy.lng());
    }


}

Open in new window


Here's a screenshot of what my current code looks like:
Google Maps
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2017
Distinguished Expert 2018
Commented:
Some reference URL's
https://developers.google.com/maps/documentation/javascript/examples/drawing-tools
https://developers.google.com/maps/documentation/javascript/examples/polygon-arrays
Sample code
<!doctype html>
<html>
<head>
<title>Test</title>
</head>
<body>
<div id="map-canvas" style="width: 100%; height: 500px"></div>
<div><textarea type="text" id="vertices" rows="10" cols="100"></textarea></div>
<script src="http://code.jquery.com/jquery.js"></script>

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=drawing"></script>

<script type="text/javascript">


function initialize() {
  var mapOptions = {
    center: new google.maps.LatLng(-34.397, 150.644),
    zoom: 8
  };

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

  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.CIRCLE,
        google.maps.drawing.OverlayType.POLYGON,
        google.maps.drawing.OverlayType.RECTANGLE
      ]
    },
  polygonOptions: {
    editable: true
  },  
    circleOptions: {
      fillColor: '#ffff00',
      fillOpacity: 1,
      strokeWeight: 5,
      clickable: false,
      editable: true,
      zIndex: 1
    }
  });
  
  google.maps.event.addListener(drawingManager, "overlaycomplete", function(event){
       overlayClickListener(event.overlay);
    $('#vertices').val(event.overlay.getPath().getArray());
  });

  drawingManager.setMap(map);
}
function overlayClickListener(overlay) {
console.log('clicked');  
    google.maps.event.addListener(overlay, "mouseup", function(event){
        $('#vertices').val(overlay.getPath().getArray());
    });
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</body>
</html>

Open in new window

Author

Commented:
Thank you for the help! This is extremely helpful for my project and it has give me a better idea on how to grab values of the new coordinates.
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
You are welcome.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial