I am trying to create an interactive map that visualizes certain data.
I used leaflet map and a topojson layer on it. Next, I tried to add static labels on each of the topojson polygons using leaflet label plugin i.e. the labels should always be there and should not react to mouseover event.
I tried implementing bindLabel()
method with noHide:true
, but it didn't seem to work. Therefore, I implemented the solution provided to this question Simple label on a leaflet (geojson) polygon . I succeeded in adding static labels.
Then, I have a function that removes a topojson polygon on click event. I was supposed to remove the label on THAT PARTICULAR POLYGON ONLY after it is removed but I cannot seem to implement that.
Here's what I did to add topojson layer and labels:
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);
}
}
So far, this code removes the topojson polygon when it is clicked, but the label is still there.
I have to remove the label which is on that particular polygon which is removed, but keep the labels on other polygons.
Also, when the other polygon is clicked, it should be removed but the previously removed label should be retained since the previously removed polygon is also retained.
I cannot, for the life of me think of how to implement that. Please help me.