Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Maps v3 - Delete vertex on Polygon

Google Maps has the Drawing library to draw Polylines and Polygons and other things.

Example of this functionality here: http://gmaps-samples-v3.googlecode.com/svn-history/r282/trunk/drawing/drawing-tools.html

I want, when drawing and editing the polygon, to be able to delete one point/vertex on the path. The API docs haven't seemed to hint at anything.

like image 686
James F Avatar asked Jan 12 '12 07:01

James F


People also ask

How do you delete a polygon in Google Maps?

To remove a polygon from the map, call the setMap() method passing null as the argument. In the following example, bermudaTriangle is a polygon object: bermudaTriangle. setMap(null);

Can I draw a polygon on Google Maps?

Draw a path or polygonTo make a path or polygon into a 3D object, click Altitude. A "New Path" or "New Polygon" dialog will pop up. You may need to move it out of the way before moving on to the next step. To draw the line or shape you want, click a start point on the map and drag.


2 Answers

Google Maps now provides a "PolyMouseEvent" callback object on events that are triggered from a Polygon or Polyline.

To build on the other answers which suggested a solution involving a right click, all you would need to do is the following in the latest versions of the V3 API:

// this assumes `my_poly` is an normal google.maps.Polygon or Polyline var deleteNode = function(mev) {   if (mev.vertex != null) {     my_poly.getPath().removeAt(mev.vertex);   } } google.maps.event.addListener(my_poly, 'rightclick', deleteNode); 

You'll notice that any complex calculations on whether or not we are near the point are no longer necesary, as the Google Maps API is now telling us which vertex we've clicked on.

Note: this will only work while the Polyline/Polygon is in edit mode. (Which is when the vertices you might want to delete are visible.)

As a final thought, you could consider using a click or double click event instead. "Click" is smart enough to not trigger on a drag, though using a single click trigger might still surprise some of your users.

like image 142
Sean Ouimet Avatar answered Sep 21 '22 18:09

Sean Ouimet


This is currently an outstanding feature request (acknowledged by Google), issue 3760.

Here's my solution: http://jsbin.com/ajimur/10. It uses a function that adds a delete button to the passed in polygon (below the undo button).


Alternatively, someone suggested this approach: right-click to delete closest vertex, which works fine but is somewhat lacking in UI finesse. I built on the code from the link to check if the click was inside (or within 1 pixel of) the node - in a JSBin here: http://jsbin.com/ajimur/.

EDIT: as Amr Bekhit pointed out - this approach is currently broken, as the events need to be attached to the polygon.

like image 20
Ian Grainger Avatar answered Sep 17 '22 18:09

Ian Grainger