如何删除 OpenLayers 5 中的绘图?

1 javascript drawing openlayers node.js

I am using OpenLayers to create a map that allows a user to draw on it. The drawing options are implemented from the official docs and do work. https://openlayers.org/en/latest/examples/draw-features.html

I tried to give the user an option to delete his former drawing. By holding the key "A" you can see the users selection. Now this selected drawings should be deleted in the moment the key is released (but nothing happened).

var select = new Select();

window.addEventListener('keydown', function (event) {
    // A
    if (event.keyCode == 65) {
        map.addInteraction(select);
    }
});
window.addEventListener('keyup', function (event) {
    if (event.keyCode == 65) {
        var selectedFeatures = select.getFeatures();
        selectedFeatures.clear();
        map.removeInteraction(select);
    }
});
Run Code Online (Sandbox Code Playgroud)

What am I missing?

小智 5

由于我缺少发表评论的声誉,因此我必须将此作为答案发布。首先,keyCode弃用,现在您应该只使用event.key,这也使您的代码更清晰,因为关键是"a".

另一个问题是,您通过 select.getFeatures() 获取选定的功能,它返回一个功能或一个集合(请参阅API)。该功能没有clear方法,但您可以获取图层,然后从其源中删除所选功能。这可能看起来像这样:

var selectSource = select.getLayer(selectedFeature).getSource();
selectSource.removeFeature(selectedFeature);
Run Code Online (Sandbox Code Playgroud)

也就是说,假设您选择了一个特征,否则您可以遍历所选特征。