我尝试创建一个可以创建功能的代码,并在不遵守某些规则的情况下将其删除。 (在这个例子中,我只是在他创建后将其删除)
下面是我的代码,我创建了地图,并允许在其上创建多边形。接下来,我尝试在触发事件支出时删除它。
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)
我知道这是因为我的功能尚不存在,并且它将在事件结束后创建。因此,我的问题是,功能创建后如何删除?
任何人都可以解释我该怎么做?
预先感谢;)
答案 0 :(得分:1)
如果检查失败,您是否在drawend
中尝试过类似的操作:
source.once('addfeature', (event) => {
const feature = event.feature;
source.removeFeature(feature);
});
此方法仅侦听一次'addfeature'事件,然后删除该侦听器。