angular7 - 如何使用 ngx-leaflet-draw 为 ngx-leaflet 创建自定义绘制按钮
问题描述
我想创建一个自定义按钮,它可以在单击时启用折线抽屉。它类似于How to click a button and start a new polygon without using the Leaflet.draw UI,但我想用angular (7)
,ngx-leaflet
和ngx-leaflet-draw
.
这是我的角度项目链接中的改编代码:
// app.component.ts
import * as L from 'leaflet';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
allDrawnItems = new L.FeatureGroup();
options = {
layers: [
tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 18, attribution: '...' })
],
zoom: 5,
center: latLng(51.9487949, 7.6237527)
};
drawOptions = {
position: 'bottomright',
draw: {
circlemarker: false,
polyline: true
},
featureGroup: this.allDrawnItems
}
constructor() {}
ngOnInit() {
this.options = {
layers: [
tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {maxZoom: 18, attribution: '...' })
],
zoom: 12,
center: latLng(51.9487949, 7.6237527)
};
this.drawOptions = {
position: 'bottomright',
draw: {
circlemarker: false,
polyline: true
},
featureGroup: this.allDrawnItems
}
}
btn_drawPolygon() {
var polylineDrawer = new L.Draw.Polyline(this.map); // <-- throws error
polylineDrawer.enable();
}
onDrawReady(event) {
console.log(event.layer);
}
}
这是我的html:
// app.component.html
<div style="text-align:center; margin-top: 64px;" fxFlex>
<div fxFlex
leaflet
[leafletOptions]="options">
<div
leafletDraw
[leafletDrawOptions]="drawOptions"
(leafletDrawCreated)="onDrawReady($event)"></div>
</div>
<button (click)="btn_drawPolygon()" mat-raised-button color="primary" fxFlex style="height: 38px;">draw polyline</button>
如果我单击“绘制折线”按钮,则会收到错误消息:
ERROR TypeError: Cannot read property 'overlayPane' of undefined
at NewClass.initialize (leaflet.draw.js:8)
at NewClass.initialize (leaflet.draw.js:8)
at new NewClass (leaflet-src.js:301)
我的代码有什么问题?
解决方案
好吧。我忘了使用 leafletMapReady 函数绑定地图:
// app.component.html
<div fxFlex
leaflet
[leafletOptions]="options"
(leafletMapReady)="onMapReady($event)"> <!-- added -->
<div
leafletDraw
[leafletDrawOptions]="drawOptions"
(leafletDrawCreated)="onDrawReady($event)"></div>
在使用 onMapReady 函数并将地图绑定到 this.map 之后,它就像一个魅力:
onMapReady(map: L.Map) {
console.log("ON MAP READY CALLED");
console.log(this.map);
this.map = map;
};
推荐阅读
- kubernetes - 非标准端口上的 haproxy-ingress 负载平衡 http
- python - 在 Kubernetes 中发布文件 1 分钟后超时
- mysql - MySQL:如何连接两个单独的列并将其作为结果返回?
- javascript - 我的变量是作用域的,我需要它是全局的
- php - Dockerfile | 高山 | Nginx | php7 | MongoDB | 雷迪斯
- node.js - 如何在一个查询中选择两个表在sequelize
- c++ - 与 Visual Studios (c++) 同步时如何组织您的 github 存储库?
- progressive-web-apps - 渐进式 Web 应用图像资产缓存:预缓存还是运行时缓存?
- javascript - 将孩子的属性应用到父母
- postgresql - PostgreSql SET configuration_parameter 来自存储过程