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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20789385/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 19:18:58  来源:igfitidea点击:

How can I detect when an editable polygon is modified?

javascriptgoogle-mapseventsgoogle-maps-api-3

提问by

How can I detect when an editable polygon is modified (point moved, point added, point removed) or dragged? The Google Maps API docs only list mouse events for Polygons.

如何检测可编辑多边形何时被修改(点移动、添加点、删除点)或拖动?Google Maps API 文档仅列出了 Polygons 的鼠标事件

回答by

Polygonsare made of Paths which are just MVCArrays(in this case, they're a list of LatLng objects). MVCArrays have three events: insert_at, remove_at, and set_at. We can use those events to detect changes in the points of the Polygon.

多边形由 Paths 组成,Paths 只是MVCArrays(在这种情况下,它们是 LatLng 对象的列表)。MVCArrays有三个事件:insert_atremove_at,和set_at。我们可以使用这些事件来检测多边形点的变化。

There are also drag events for polygons: dragstart, drag, and dragend. It's best to listen for dragendif you want to know that a shape was just dragged.

也有多边形拖动事件dragstartdrag,和dragenddragend如果您想知道刚刚拖动的形状,最好听听。

All together, we can detect any changes to a polygon:

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

// 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
});