如何检测何时添加顶点

问题描述 投票:0回答:1

我需要检测在绘制或编辑顶点时何时添加了一个顶点。我现在这样做的方式有效,但看起来很笨拙,所以我想知道我是否忽略了一个“可观察的”事件,或者是否有更优雅的方式来捕捉新的顶点。

我现在正在做的是将自己的属性添加到要素中,该要素跟踪有多少个顶点然后根据每个“更改”事件的实际顶点数进行检查,基本上:

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'事件或类似的东西我忽略了吗?

编辑:根据迈克的建议,我已经在下面修改了我的代码,它仍然感觉很糟糕。我将自己的'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);
openlayers openlayers-3
1个回答
1
投票

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

  var draw = new ol.interaction.Draw({
    source: source,
    type: 'LineString',
    condition: function(evt) {
      var res = ol.events.condition.noModifierKeys(evt);
      var features = draw.getOverlay().getSource().getFeatures();
      if (res && features.length) {
        console.log(features[0].getGeometry().getCoordinates().length);
      }
      return res;
    }
  });
© www.soinside.com 2019 - 2024. All rights reserved.