如何在 openlayers 回调后删除功能

How can I delete a feature after a callback on openlayers

我尝试创建一个可以创建功能的代码,如果它不遵守某些规则则将其删除。 (在这个例子中,我只是在他创建后删除它)

下面是我的代码,我创建了一个地图并允许在其上创建一个多边形。接下来我尝试在触发事件 drawend 时将其删除。

 init(){
        this.message = "";
        var raster = new TileLayer({
            source: new XYZ({
                url: 'http://mt1.google.com/vt/lyrs=m&x={x}&y={y}&z={z}',
                attributions: [
                '© Google','<a href="https://developers.google.com/maps/terms">Terms of Use.</a>'
                ]
            })
        });

        this.source = new VectorSource();

        this.vector = new VectorLayer({
            source: this.source
        });

        this.map = new Map({
            layers: [raster, this.vector],
            target: 'map',
            view : new View({
                center: [0,0],
                zoom : 4
            })
        }); 

            this.addInteraction();


    }

    addInteraction() {
        var self = this;
        this.draw = new Draw({
            source: this.source,
            type: "Polygon"
        });
        this.draw.on('drawend', function (e) {
            self.message = "";
            self.map.removeInteraction(self.draw);
            self.selectedFeature = e.feature;

            self.removeSelectedFeature();

            // This works but I don't like this solution
            //setTimeout(function(){self.removeSelectedFeature()}, 1);

            self.geoJSON = self.getCoord();
        });
        this.map.addInteraction(this.draw);
    }

    removeSelectedFeature()
    {
        this.source.removeFeature(this.selectedFeature);
        this.selectedFeature = null;
        this.validated = false;
        this.addInteraction();
    }

但是当我尝试执行这段代码时,出现了这个错误:

core.js:14597 ERROR TypeError: Cannot read property 'forEach' of undefined
    at VectorSource.removeFeatureInternal (Vector.js:951)
    at VectorSource.removeFeature (Vector.js:939)
    at MapComponent.push../src/app/map/map.component.ts.MapComponent.removeSelectedFeature (map.component.ts:106)
    at Draw.<anonymous> (map.component.ts:97)
    at Draw.boundListener (events.js:41)
    at Draw.dispatchEvent (Target.js:99)
    at Draw.finishDrawing (Draw.js:872)
    at Draw.handleUpEvent (Draw.js:578)
    at Draw.handleEvent (Pointer.js:132)
    at Draw.handleEvent (Draw.js:524)

我知道这是因为我的功能还不存在,它将在活动结束后创建。因此我的问题是,如何在创建功能后将其删除?

  1. 我尝试使用事件按钮,但这不是一个好主意我希望用户不需要单击按钮来执行检查。
  2. 我尝试使用 setTimeout(正如我们在注释代码中看到的那样),但我不喜欢这个解决方案(即使它有效)

任何人都可以向我解释我该如何完成这项工作?

提前致谢;)

你有没有在你的 drawend 中尝试过这样的事情,如果你的检查失败:

source.once('addfeature', (event) => {
  const feature = event.feature;
  source.removeFeature(feature);
});

这会监听一次 'addfeature' 事件,然后删除监听器。