0

I am trying to show/hide a legend when a certain overlay is clicked, but can't seem to get the legend to hide when the overlay is unclicked.

Here's my sample setup:

//establish the data
var popDensity = L.geoJson(popDensity, {
    onEachFeature: onEachFeature
    style: myCustomstyle
});

//Create the legend control
var popuLegend = L.control();
popuLegend.onAdd = function(map){
    var container = L.DomUtil.create('div', 'info');
    container.innerHTML = '<h3>Population</h3><ul id="popuLegend"><li>1000+</li><li>500+</li><li>etc..</li></ul>';
    return container;
};

My layers control:

var baseMaps = {
    "Base map 1": basemapOne,
    "Base map 2": basemapTwo
};

var ethnicGroups = {
    "Pashtun": pashtun,
    "Tajik": tajik,
    "etc..": etc,
    "District Population": popDensity
};

map.fitBounds(pashtun.getBounds());
L.control.layers(baseMaps, ethnicGroups).addTo(map);

Here's my event handler:

map.on('overlayadd', function(eventLayer){
    if (eventLayer.name === 'District Population'){
        map.addControl(popuLegend);
    } else {
        map.removeControl(popuLegend);
    }
};

This setup successfully adds the legend control when the 'District Population' overlay is checked, but when it is unchecked, the legend does not remove itself. When you check it again, another copy of the legend is added on top of the previous legend. Any tips?

0

I think you need to listen for 'overlayremove' to listen to the District Population being unchecked. Give this a shot, not entirely sure.

map.on('overlayadd', function(eventLayer){
    if (eventLayer.name === 'District Population'){
        map.addControl(popuLegend);
    } 
};

map.on('overlayremove', function(eventLayer){
    if (eventLayer.name === 'District Population'){
         map.removeControl(popuLegend);
    } 
};

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.