如何检测何时添加顶点

时间:2019-04-20 18:07:41

标签: openlayers openlayers-3

我需要检测在绘制或编辑顶点时已将其添加到线中。我的操作方式现在可以使用,但是看起来很笨拙,所以我想知道我是否忽略了一个“可观察的”事件,或者是否有一种更优雅的捕获新顶点的方法。

我现在正在做的是在功能中添加我自己的属性,该功能可以跟踪存在的顶点数量,然后基本上在每次“更改”事件中对照实际的顶点数量进行检查:

draw.on('drawstart',
  function(evt) {
    var sketch = evt.feature;
    var sketchGeom = sketch.getGeometry();
    // the 'change' event will will fired by mouse move or mouse click
    sketchGeom.on('change', function(evt) {
      // check the actual number of verticies against
      // my 'nodeCount' to see if the 'change' event
      // has created a vertex
    });
    sketchGeom.set('nodeCount', 1);  // add my own property to track the number of verticies
  },
  this);

我见过的另一种方法是观察地图点击,而不是观察地图项的更改,但这不适合我的流程,也不能观看“更改”事件。

那么有'vertexAdded'事件或我忽略的类似事件吗?

编辑:基于Mike的建议,我在下面对代码进行了一些修改,但仍然感觉很笨拙。我将自己的'nodeCount'属性添加到几何图形中,该属性在单击鼠标时增加。然后,我可以根据几何的实际长度检查我的'nodeCount'属性。如果OL由于鼠标移动而添加了一个顶点,则几何图形的长度将大于我的计数,并且我知道我正在处理鼠标移动,否则它们相等并且我正在处理点击。

var draw = new Draw({  // import Draw from 'ol/interaction/Draw.js';
  source: source,
  type: 'LineString',
  condition: function(evt) {
    var res = noModifierKeys(evt);  // import {noModifierKeys} from 'ol/events/condition.js';
    var features = draw.getOverlay().getSource().getFeatures();
    if (res && features.length) {
      let geom = features[0].getGeometry();
      geom.set('nodeCount', geom.getCoordinates().length); // add my own property
    }
    return res;
  }
});

draw.on('drawstart',
  function(evt) {
    var sketchGeom = evt.feature.getGeometry();
    // the 'change' event will be fired by mouse-move or mouse-click
    sketchGeom.on('change', function(evt) {
      let geom = evt.target;
      let verticesLength = geom.getCoordinates().length;
      let nodeCount = geom.get('nodeCount') // fetch my property

      if (verticesLength === nodeCount) { // a new vertex has been created by a mouse click
        // handle a mouse-click
      } else if (verticesLength > nodeCount) { // a new vertex has been created by mouse move (not by a click, which would have incremented nodeCount)
        // handle a mouse-move
      }
      // do things that are common to mouse-move and mouse-click
    });
  },
this);

1 个答案:

答案 0 :(得分:1)

您可以将默认条件函数包装到自己的函数中,以捕获添加顶点的任何单击。在OL5中,可以通过getOverlay()获得草图功能

YEARFRAC