Openlayers 如何检测何时添加顶点
在绘制或编辑直线时,我需要检测顶点何时被添加到直线中。我现在这样做是可行的,但是看起来相当笨拙,所以我想知道我是否忽略了一个“可观察的”事件,或者是否有一种更优雅的方法来捕捉新的顶点 我现在做的是将我自己的属性添加到功能中,该功能跟踪有多少个顶点,然后根据每个“更改”事件的实际顶点数进行检查,基本上:Openlayers 如何检测何时添加顶点,openlayers,openlayers-3,Openlayers,Openlayers 3,在绘制或编辑直线时,我需要检测顶点何时被添加到直线中。我现在这样做是可行的,但是看起来相当笨拙,所以我想知道我是否忽略了一个“可观察的”事件,或者是否有一种更优雅的方法来捕捉新的顶点 我现在做的是将我自己的属性添加到功能中,该功能跟踪有多少个顶点,然后根据每个“更改”事件的实际顶点数进行检查,基本上: draw.on('drawstart', function(evt) { var sketch = evt.feature; var sketchGeom = sketch.g
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);
我见过的另一种方法是观察地图点击,而不是观察功能的变化,但这不适合我的流程以及观察“变化”事件
那么,有没有我忽略的“顶点添加”事件或类似事件
编辑:根据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);
您可以将默认条件函数包装在自己的函数中,以捕获添加顶点的任何单击。在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;
}
});