如何在删除包含它的 topojson 层时删除传单标签

How to remove a leaflet label when a topojson layer containing it is removed

我正在尝试创建可视化特定数据的交互式地图。

我在上面使用了传单地图和一个 topojson 层。接下来,我尝试使用传单标签插件在每个 topojson 多边形上添加静态标签,即标签应该始终存在并且不应对鼠标悬停事件做出反应。

我尝试用 noHide:true 实现 bindLabel() 方法,但它似乎没有用。因此,我实现了针对这个问题 Simple label on a leaflet (geojson) polygon 提供的解决方案。添加静态标签成功

然后,我有一个函数可以在单击事件时删除一个 topojson 多边形。我应该只在 THAT PARTICULAR POLYGON 上的标签被移除后才移除它,但我似乎无法实现它。

这是我添加 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 多边形,但标签仍然存在。

我必须删除已删除的特定多边形上的标签,但保留其他多边形上的标签。

此外,当单击另一个多边形时,它应该被删除,但是之前删除的标签应该被保留,因为之前删除的多边形也被保留。

我一辈子都想不出如何实现它。请帮我。

说明

首先,您需要维护一个 labels_array 存储标签的地方,以便在需要时移除。

其次,维护另一个 unique_property_array,您需要在其中存储您在 topojson 文件中拥有的唯一 属性。

第三,当用户点击任何特征时,我们将获得点击的特征属性并与我们的unique_property_array匹配,得到索引匹配的值并从 labels_array 中删除该索引。此外,添加标签 remove previously。

代码块

首先,需要三个全局变量

var labels_array=[];
var unique_property_array=[];
var labelIndexToRemove='';

其次,这样修改你的addLabel()函数

function addLabel(layer) {
    var label = new L.Label();  
    label.setContent(layer.feature.properties.REGION);
    label.setLatLng(layer.getBounds().getCenter());
    map.showLabel(label);

    //below two lines are new
    labels_array.push(label);
    unique_property_array.push(layer.feature.properties.region);
}

最后,这样修改你的clickAction()函数

function clickAction(e) {
    regionLayer.eachLayer(function(layer){
        map.addLayer(layer);
    });
    var layer = e.target;
    map.removeLayer(layer);

    //below lines are new
    if(labelIndexToRemove!=''){
        map.addLayer(labels_array[labelIndexToRemove]);
    }
    labelIndexToRemove= unique_property_array.indexOf(e.target.feature.properties.region);
    map.removeLayer(labels_array[labelIndexToRemove]);
}

试试这个,告诉我它是否有效。祝你好运