我正在尝试创建一个交互式地图,用于可视化某些数据。
我使用了leaflet地图和一个topojson图层。接下来,我尝试使用leaflet标签插件在每个topojson多边形上添加静态标签,即标签应始终存在且不应对鼠标悬停事件做出反应。
我尝试使用bindLabel()
方法,并使用noHide:true
,但似乎没有起作用。因此,我实现了这个问题提供的解决方案Simple label on a leaflet (geojson) polygon。我成功地添加了静态标签。
然后,我有一个函数,在单击事件中删除topojson多边形。之后我应该只删除该特定多边形上的标签,但我似乎无法实现这一点。
以下是我添加topojson图层和标签的方法:
function addRegions(map) {
var regionLayer = new L.TopoJSON();
$.getJSON('region.topo.json').done(addRegionData);
function addRegionData(topoData) {
regionLayer.addData(topoData);
regionLayer.addTo(map);
regionLayer.eachLayer(addLabel);
regionLayer.eachLayer(handleLayer);
}
function handleLayer(layer) {
layer.on({
click: clickAction
});
}
// Here's the code for adding label
function addLabel(layer) {
var label = new L.Label();
label.setContent(layer.feature.properties.REGION);
label.setLatLng(layer.getBounds().getCenter());
map.showLabel(label);
}
// Here's the code that removes a polygon when it is clicked and retains the previously removed polygon
function clickAction(e) {
regionLayer.eachLayer(function(layer){
map.addLayer(layer);
});
var layer = e.target;
map.removeLayer(layer);
}
}
目前,这段代码可以在点击topojson多边形时移除它,但是标签仍然存在。
我需要删除特定多边形上的标签,但保留其他多边形上的标签。
此外,当单击其他多边形时,应该移除它,但是之前移除的标签应该保留,因为先前移除的多边形也被保留了。
我想不出如何实现,请帮帮我。