Editing polygons of Google Maps - get latlng position on the mouse button

I am trying to write a simple snap function to edit a polygon in Google Maps v3.9

I have several polygons on the map that can be made editable one at a time. When you make it editable, I will also add a listener to it to invoke when the vertex is being dragged.

Since there is no drag event for google.maps.Polygon , I add a mousedown listener, which checks if the vertex is under the cursor, and if it adds a mouseup listener. The code inside this mouseup listener checks the vertices of all other polygons and updates the drag vertex if a match is found.

This works well except for one problem. Validation is performed using the latLng PolyMouseEvent returned by the mouseup listener. This property indicates the location of the vertex before it is dragged, and I cannot find a way to refer to the vertex in its new position.

 dragListener = google.maps.event.addListener( poly1, "mousedown", function( dragData ) { // if dragging a vertex if ( dragData.vertex != null ) { // perform snap on mouseup snapListener = google.maps.event.addListener( poly1, "mouseup", function( mouseData ) { var editingVertex = mouseData.vertex; var draggedLatLng = mouseData.latLng; // code here to compare draggedLatLng with latLng of editingVertex // and perform snap, which seems to work fine as is... } } } 
+4
source share
1 answer

Polygons are a set of paths, and MVCArrays paths are LatLng , so we can listen to the set_at event on each path in the polygon that tells us when the point was moved.

 poly1.getPaths().forEach(function(path, index){ google.maps.event.addListener(path, 'set_at', function(index, oldLatLng){ var newLatLng = path.getAt(index); // Now you have both the old and new position }); }); 

If you know that your polygons never have more than one path (inner rings), you can simply do this:

 google.maps.event.addListener(poly1.getPath(), 'set_at', function(index, oldLatLng){ var newLatLng = path.getAt(index); }); 

Although I recommend the first, because you never know when a polygon with several paths can somehow penetrate.

+3
source

All Articles