Reputation: 113
I am trying to write a simple snapping function for editing a polygon in Google Maps v3.9
I have several polygons on the map, which can be made editable one at a time. When one is made editable, I also add a listener to it, to trigger when a vertex has been dragged.
As there is no drag event for google.maps.Polygon
, I add a mousedown
listener, which checks if a vertex is beneath the cursor, and if so adds a mouseup
listener.
The code within this mouseup
listener checks against the vertices of all other polygons, and updates the dragging vertex if a close match is found.
This works well, except for one problem. The check is performed using the latLng
property of the PolyMouseEvent
returned by the mouseup
listener. This property points to the location of the vertex before it was dragged, and I can't find a way to reference 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...
}
}
}
Upvotes: 5
Views: 1677
Reputation:
Polygons are a collection of paths, and paths are MVCArrays of LatLng objects, so we can listen for the set_at
event on each path in the polygon which tells us when a point has been 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 then one path (inner rings) then you can just do this:
google.maps.event.addListener(poly1.getPath(), 'set_at', function(index, oldLatLng){
var newLatLng = path.getAt(index);
});
Though I recommend the first one because you never know when a polygon with multiple paths might somehow sneak in.
Upvotes: 4