Drawing a Polygon with Google Maps

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
danswillAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Julian HansenCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
danswillAuthor 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.
Julian HansenCommented:
You are welcome.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.