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

荒凉一梦 提交于 2019-12-04 08:02:08

Explaination

Firstly, you need to maintain an labels_array where you store your labels so as to remove when required.

Secondly, maintain another unique_property_array where you need to store the unique property you have in your topojson file.

Thirdly, when user would click on any feature, we would get the clicked feature property and match with our unique_property_array, getting the index of the matched value and remove that index from labels_array. Additionally, add the label remove previously.

CodeBlock

Firstly, you need to have three global variables

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

Secondly, modifiy your addLabel() function this way

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);
}

Lastly, modify your clickAction() function this way

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]);
}

Try this and tell me if it works. Good luck

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!