好的,我自己根据评论找到答案。图例只能添加到地图本身,而不能添加到图层。但使用以下代码时,地图不可用:
private createChart() {
this.options = {
layers: [
tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 18, attribution: '...' }),
],
zoom: 6,
center: latLng(51.5167, 9.9167)
};
}
为了获得由传单本身制作的地图,您需要将其绑定。这在模板文件中完成:
<div style="height: 700px;"
leaflet
[leafletOptions]="options"
[leafletLayersControl]="layersControl"
(leafletMapReady)="onMapReady($event)">
</div>
然后我定义了onMapReady()函数,如下所示:
onMapReady(map: Map) {
this.updateChart();
// Do stuff with map
map.on('baselayerchange', (eventLayer) => {
const v1 = this.min;
const v2 = this.min + Math.round((this.max - this.min ) / 2);
const v3 = this.max;
const legend = new (L.Control.extend({
options: { position: 'bottomright' }
}));
const vm = this;
legend.onAdd = function (map) {
const div = L.DomUtil.create('div', 'legend');
const labels = [
'Sales greater than ' + v1,
'Sales greater than ' + v2,
'Sales equal or less than ' + v3
];
const grades = [v1+ 1, v2+ 1, v3 ];
div.innerHTML = '<div><b>Legend</b></div>';
for (let i = 0; i < grades.length; i++) {
div.innerHTML += '<i style="background:' + vm.getColor(grades[ i ], v3, v1) + '"> </i> '
+ labels[i] + '<br/>';
}
return div;
};
legend.addTo(map);
});
}
图例仅在地图准备就绪后显示。贴图是创建的第一件事,然后图层出现。因此,我在onMapReady()中调用了updateChart(),以访问每个层的最小值和最大值。
仍然存在一个问题,即在更改图层时添加了另一个图例。但这与这个问题无关。