4
votes

I have a leaflet map set to change styles based on a category when a user clicks a button.

Live map: http://maneesha.github.io/test_map.html

Source code: https://github.com/maneesha/maneesha.github.io

There is a legend for each style. My problem is I can't get the old legend to disappear when another button is clicked (or that button is clicked again). So you'll see on the map each time you click, a new legend appears.

Putting

map.removeControl(legend);

in the click function does not work and results in this in the js console:

Uncaught TypeError: Cannot read property 'removeFrom' of undefined

Any ideas?

EDIT: Repos above have been changed. Live site no longer exists; source code is at https://github.com/maneesha/leaflet_map_with_styles_and_legends

1

1 Answers

2
votes

You're assigning the variable legend in the handler function of the click event on change-gender. If you do that, legend will only be available in that function. If you declare var legend; before the click handler and then in the click handler change: var legend = L.control({position: 'topright'}); to legend = L.control({position: 'topright'}); legend will be available in the global scope so you can reach it from every function within the global scope.

This won't work:

document.getElementById('change-gender').addEventListener('click', function () {
    var genderLegend = L.control({'position': 'topright'}).addTo(map);
});

console.log(genderLegend) // returns undefined

This will:

var genderLegend;

document.getElementById('change-gender').addEventListener('click', function () {
    genderLegend = L.control({'position': 'topright'}).addTo(map);
});

console.log(genderLegend) // returns the legend instance