javascriptleafletmapboxtilemill

Button for layers are always in active state, legend persists for 1st layer when 2 layers are added


I have a mapbox and tilemill layer problem:

Check out my code here: http://bl.ocks.org/marishaf/3cc9bfbeb412c1120e93

Layer buttons ALWAYS look like they're in the "active" mode, although they still load and unload layers.

Legends load for each layer (legends exist for Public Land and Zoning layers), but if you load both and then try to remove both layers, the legend persists for the first layer loaded.

The legend persists also with tooltips. For example, if you load a layer with a legend first (only happens if layers are loaded in this order) and then a layer with tooltips (for example Point Source Pollution) and mouse over a point so that the tooltip is called up and then try to remove the layer with the legend, the legend persists.


Solution

    1. Remove "link.className = 'active';" before onclick function.
    2. Change "if (map.hasLayer(layer))" statement to be more similar to the "else" one ("layer" instead of "thelayer" and only one "className" change).

    Snippet:

    link.href = '#';
    // remove line that was here
    link.innerHTML = name;
    
    
    link.onclick = function(e) {
        e.preventDefault();
        e.stopPropagation();
    
        if (map.hasLayer(layer)) {
            map.removeLayer(layer);
            map.removeLayer(gridlayer);
            // you had "thelayer", but it should be "layer":
            map.legendControl.removeLegend(layer.getTileJSON().legend);
            // change two lines that were here to the following:
            this.className = '';
        } else {
            map.addLayer(layer);
            map.addLayer(gridlayer);
            this.className = 'active';
            map.legendControl.addLegend(layer.getTileJSON().legend);
    
        }
           thelayer = layer;  
    
    };
    

    Sorry for the messy explanation, but you were asking two questions at once, and this is the cleanest way I can think to answer.