Event after modifying polygon in Google Maps API v3

    google.maps.event.addListener(yourPolygon.getPath(), 'insert_at', function(index, obj) {
           //polygon object: yourPolygon
    });
    google.maps.event.addListener(yourPolygon.getPath(), 'set_at', function(index, obj) {
           //polygon object: yourPolygon
    });

The above code is working for me. Where set_at is fired when we modify a polygon area from a highlighted dot (edges) and insert_at is fired when we drag point that is between highlighted edges.

I used them in the polygoncomplete event and after loading a polygon from the database. It is working fine for them.


To avoid the problems mentioned with set_at and dragging, I added the following, which disables event broadcasting for set_at when the drawing is being dragged. I created a class that extends the polygon class, and added this method:

 ExtDrawingPolygon.prototype.enableCoordinatesChangedEvent = function(){
  var me = this,
      superClass = me.superClass,
      isBeingDragged = false,
      triggerCoordinatesChanged = function(){
         //broadcast normalized event
         google.maps.event.trigger(superClass, 'coordinates_changed');
      };

  // If the overlay is being dragged, set_at gets called repeatedly,
  // so either we can debounce that or ignore while dragging,
  // ignoring is more efficient.
  google.maps.event.addListener(superClass, 'dragstart', function(){
    isBeingDragged = true;
  });

  // If the overlay is dragged
  google.maps.event.addListener(superClass, 'dragend', function(){
    triggerCoordinatesChanged();
    isBeingDragged = false;
  });

  // Or vertices are added to any of the possible paths, or deleted
  var paths = superClass.getPaths();
  paths.forEach(function(path, i){
    google.maps.event.addListener(path, "insert_at", function(){
      triggerCoordinatesChanged();
    });
    google.maps.event.addListener(path, "set_at", function(){
      if(!isBeingDragged){
        triggerCoordinatesChanged();
      }
    });
    google.maps.event.addListener(path, "remove_at", function(){
      triggerCoordinatesChanged();
    });
  });
};

It added a "coordinates_changed" event to the polygon itself, so other code can just listen for a nice, single, simplified event.


I solved it by calling .getPath() and putting the listener inside the listener which is called every time a shape is clicked. I think the Google API documentation is not very clear on how to use the set_at so it may be useful for other people too.

// Add an event listener that selects the newly-drawn shape when the user
// mouses down on it.
var newShape = e.overlay;
newShape.type = e.type;
google.maps.event.addListener(newShape, 'click', function() {
    google.maps.event.addListener(newShape.getPath(), 'set_at', function() {
        console.log("test");
    });

    google.maps.event.addListener(newShape.getPath(), 'insert_at', function() {
        console.log("test");
    });
    setSelection(newShape);
});