如何在 OL3 中将 drawend 添加到源后捕获事件?

How to catch event after drawend added to source in OL3?

我想在将每个要素绘制到地图后更新列表。

当我使用drawend捕捉绘图的完成时,正在绘制的特征此时尚未添加到矢量源。

所以

var draw = new ol.interaction.Draw({
    source: source,
    type: 'Point'
});

draw.on('drawend', function () {
    console.log(source.getFeatures().length)
});

map.addInteraction(draw);

添加第一个点后将输出 0。

绘制完成并且要素已添加到矢量源后,如何捕捉地图的状态?因此,我正在寻找 source.getFeatures().length 在空地图上为 1 的状态。

您可以随时尝试@jonatas 的建议。它应该做你要找的工作。 另一种解决方法是从事件本身获取当前绘制的特征并将其添加到特征数组中。检查这个

draw.on('drawend', function (e) {
var currentFeature = e.feature;//this is the feature fired the event
var restOfFeats = source.getFeatures();//rest of feats
var allFeats = restOfFeats.concat(currentFeature);//concatenate the event feat to the array of source feats
console.log(allFeats.length)
});