James F
James F

Reputation: 554

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.

Upvotes: 29

Views: 24625

Answers (6)

Ralpharoo
Ralpharoo

Reputation: 828

2020 Update

Google provides a working demo of this in their documentation which demonstrates how a to delete a vertex, or a point on the line, by right-clicking on a vertex to show a "Delete" menu.

Check out Deleting a Vertex

Deleting a Vertex

And the code for completeness (see their Github repo);

function initialize() {
  const mapOptions = {
    zoom: 3,
    center: new google.maps.LatLng(0, -180),
    mapTypeId: "terrain",
  };
  const map = new google.maps.Map(document.getElementById("map"), mapOptions);
  const flightPlanCoordinates = [
    new google.maps.LatLng(37.772323, -122.214897),
    new google.maps.LatLng(21.291982, -157.821856),
    new google.maps.LatLng(-18.142599, 178.431),
    new google.maps.LatLng(-27.46758, 153.027892),
  ];
  const flightPath = new google.maps.Polyline({
    path: flightPlanCoordinates,
    editable: true,
    strokeColor: "#FF0000",
    strokeOpacity: 1.0,
    strokeWeight: 2,
    map: map,
  });

  /**
   * A menu that lets a user delete a selected vertex of a path.
   */
  class DeleteMenu extends google.maps.OverlayView {
    constructor() {
      super();
      this.div_ = document.createElement("div");
      this.div_.className = "delete-menu";
      this.div_.innerHTML = "Delete";
      const menu = this;
      google.maps.event.addDomListener(this.div_, "click", () => {
        menu.removeVertex();
      });
    }
    onAdd() {
      const deleteMenu = this;
      const map = this.getMap();
      this.getPanes().floatPane.appendChild(this.div_);
      // mousedown anywhere on the map except on the menu div will close the
      // menu.
      this.divListener_ = google.maps.event.addDomListener(
        map.getDiv(),
        "mousedown",
        (e) => {
          if (e.target != deleteMenu.div_) {
            deleteMenu.close();
          }
        },
        true
      );
    }
    onRemove() {
      if (this.divListener_) {
        google.maps.event.removeListener(this.divListener_);
      }
      this.div_.parentNode.removeChild(this.div_);
      // clean up
      this.set("position", null);
      this.set("path", null);
      this.set("vertex", null);
    }
    close() {
      this.setMap(null);
    }
    draw() {
      const position = this.get("position");
      const projection = this.getProjection();

      if (!position || !projection) {
        return;
      }
      const point = projection.fromLatLngToDivPixel(position);
      this.div_.style.top = point.y + "px";
      this.div_.style.left = point.x + "px";
    }
    /**
     * Opens the menu at a vertex of a given path.
     */
    open(map, path, vertex) {
      this.set("position", path.getAt(vertex));
      this.set("path", path);
      this.set("vertex", vertex);
      this.setMap(map);
      this.draw();
    }
    /**
     * Deletes the vertex from the path.
     */
    removeVertex() {
      const path = this.get("path");
      const vertex = this.get("vertex");

      if (!path || vertex == undefined) {
        this.close();
        return;
      }
      path.removeAt(vertex);
      this.close();
    }
  }
  const deleteMenu = new DeleteMenu();
  google.maps.event.addListener(flightPath, "rightclick", (e) => {
    // Check if click was on a vertex control point
    if (e.vertex == undefined) {
      return;
    }
    deleteMenu.open(map, flightPath.getPath(), e.vertex);
  });
}

Upvotes: 1

Ian Grainger
Ian Grainger

Reputation: 5516

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.

Upvotes: 28

user879121
user879121

Reputation:

I ran into situations where I needed to delete nodes from polygons that contained multiple paths. Here's a modification of Sean's and Evil's code:

shape.addListener('rightclick', function(event){
  if(event.path != null && event.vertex != null){
    var path = this.getPaths().getAt(event.path);
    if(path.getLength() > 3){
      path.removeAt(event.vertex);
    }
  }
});

Upvotes: 11

andro1d
andro1d

Reputation: 568

Just thought I'd contribute because I was looking for a solution for this too, here's my implementation:

if (m_event.hasOwnProperty('edge') && m_event.edge >= 0 &&
GeofenceService.polygon.getPath().getLength() > 3) {
    GeofenceService.polygon.getPath().removeAt(m_event.edge);
    return;
}

if (m_event.hasOwnProperty('vertex') && m_event.vertex >= 0 &&
GeofenceService.polygon.getPath().getLength() > 3) {
    GeofenceService.polygon.getPath().removeAt(m_event.vertex);
    return;
}

This allows for handling deletion of vertex nodes AND edge nodes, and maintains a minimum of a triangle formation polygon at all times by checking the path length > 3.

Upvotes: 2

Evil Red Robot
Evil Red Robot

Reputation: 341

I found Sean's code very simple and helpful. I just added a limiter to stop deleting when the user has only 3 nodes left. Without it, the user can get down to just one node, and can't edit anymore:

my_poly.addListener('rightclick', function(mev){
    if (mev.vertex != null && this.getPath().getLength() > 3) {
        this.getPath().removeAt(mev.vertex);
    }
});

Upvotes: 22

Sean Ouimet
Sean Ouimet

Reputation: 439

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.

Upvotes: 43

Related Questions