如何检测何时修改可编辑多边形?

时间:2013-12-26 18:27:31

标签: javascript google-maps events google-maps-api-3

如何检测何时修改可编辑多边形(点移动,点添加,移除点)或拖动? Google Maps API文档仅列出鼠标events for Polygons

1 个答案:

答案 0 :(得分:25)

Polygons由仅MVCArrays的路径组成(在这种情况下,它们是LatLng对象的列表)。 MVCArrays有三个事件:insert_atremove_atset_at。我们可以使用这些事件来检测Polygon点的变化。

还有drag events for polygonsdragstartdragdragend。如果你想知道刚刚拖动了一个形状,最好听dragend

总之,我们可以检测到多边形的任何变化:

// Loop through all paths in the polygon and add listeners
// to them. If we just used `getPath()` then we wouldn't 
// detect all changes to shapes like donuts.
polygon.getPaths().forEach(function(path, index){

  google.maps.event.addListener(path, 'insert_at', function(){
    // New point
  });

  google.maps.event.addListener(path, 'remove_at', function(){
    // Point was removed
  });

  google.maps.event.addListener(path, 'set_at', function(){
    // Point was moved
  });

});

google.maps.event.addListener(polygon, 'dragend', function(){
  // Polygon was dragged
});