简体   繁体   English

如何在OpenLayers 5中删除图形?

[英]How to delete drawing in OpenLayers 5?

I am using OpenLayers to create a map that allows a user to draw on it. 我正在使用OpenLayers创建允许用户在其上绘制的地图。 The drawing options are implemented from the official docs and do work. 绘图选项是从官方文档中实现的并且可以工作。 https://openlayers.org/en/latest/examples/draw-features.html 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. 通过按住键“ A”,您可以看到用户的选择。 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);
    }
});

What am I missing? 我想念什么?

Since i am missing the reputation to post a comment, i have to post this as answer. 由于我错过了发表评论的声誉,因此我必须将其发布为答案。 First, keyCode is deprecated , nowadays you should just use event.key , which also makes the code clearer for you, since the key is simply "a" . 首先, 不赞成使用 keyCode ,现在您应该只使用event.key ,因为key只是"a" ,这也使代码更清晰。

The other problem is, you get the selected Features by select.getFeatures(), which either returns a Feature or a Collection (see API ). 另一个问题是,您可以通过select.getFeatures()获得选定的功能,该功能返回一个功能或一个集合(请参阅API )。 The Feature does not have a clear method, but you can get the layer, and then remove the selected feature from it's source. 要素没有clear方法,但是您可以获取图层,然后从其源中删除所选要素。 This could look something like this: 可能看起来像这样:

var selectSource = select.getLayer(selectedFeature).getSource();
selectSource.removeFeature(selectedFeature);

this is, assuming you select a single feature, otherwise you could loop over the selected features. 也就是说,假设您选择了一个功能,否则可以遍历所选功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM