我有一个使用Angular 8和OpenLayers 3构建的项目。我希望能够在地图上绘制并删除多边形。我试图将此工作example移植到我的项目中。
这些是交互的组件。
使用以下代码,我可以在地图上绘制多边形,但是无法删除它们。
在sidebar.html中,将按钮设置为调用addInteraction()。
...
<mat-button-toggle value="Polygon" (change)="addInteraction()">Draw Polygon
<mat-icon>crop_original</mat-icon></mat-button-toggle>
<br><br/>
...
在侧边栏组件中,我们称为next()
...
addInteraction() {
this._sidebarService.nextDrawAOI('Polygon');
}
...
在侧边栏服务中实现了[[next()。
sidebar.service private drawAOI = new Subject<string>();
...
getDrawAOI() {
return this.drawAOI.asObservable();
}
...
nextDrawAOI(x) {
this.drawAOI.next(x);
}
在地图组件中,subscribe()被称为和。 。创建矢量层。
- 添加了绘制,捕捉和修改交互。
- 使用
- setMap(this.map)
...
private polygonLayer: VectorLayer;
private polygonSource: VectorSource;
private modify: Modify;
private draw: Draw;
private snap: Snap;
...
ngAfterViewInit() {
..
// Layers
let source = new OlXYZ({
..
});
let layer = new OlTileLayer({
..
});
// View
let view = new OlView({
..
});
const mousePositionControl = new MousePosition({
...
});
// Map
this._map = new OlMap({
controls: defaultControls().extend([
scaleLineControl, mousePositionControl
]),
interactions: OlXYZ.interactions,
target: 'map',
layers: [layer],
view: view
});
this._sidebarService.getDrawAOI().pipe(map((x) => {
this.polygonSource = new VectorSource({
wrapX: false,
dataProjection: 'EPSG:4326',
featureProjection: 'EPSG:3857'
});
this.polygonLayer = new VectorLayer({
source: this.polygonSource
});
this.modify = new Modify({source: this.polygonSource});
this._map.addInteraction(this.modify);
this._map.removeInteraction(this.draw);
this._map.removeInteraction(this.snap);
this.polygonLayer.setMap(null);
this.draw = new Draw({
source: this.polygonSource,
type: x
});
this._map.addInteraction(this.draw);
this.snap = new Snap({source: this.polygonSource});
this._map.addInteraction(this.snap);
this.polygonLayer.setMap(this._map);
return x;
})).subscribe((x) => {
console.log(x);
});
this._map.on('click', function(evt) {
在触发事件的下一行中,this.polygonLayer是undefined
var features = this.polygonLayer.getSource().getFeatures();
features.forEach((feature) => {
this.polygonLayer.getSource().removeFeature(feature);
});
});
}
问题出在这里。中,我放置了事件的处理程序。触发事件时,矢量层(又名polygonLayer)未定义。似乎矢量不会绑定到this。这是一个有约束力的问题吗?如果是这样,为什么会发生?在map.component
this._map.on('click', (evt) => {
var features = this.polygonLayer.getSource().getFeatures();
features.forEach((feature) => {
this.polygonLayer.getSource().removeFeature(feature);
});
});
自:箭头功能没有自己的this
。的this
值使用封闭的词汇范围;箭头功能遵循正常可变查找规则。因此,在搜索不是当前范围内的箭头功能最终会找到this
从其随附的范围。然后您的
this
具有正确的范围(您的组件)。