Question

I am using Leaflet to visualize map. Everything worked fine, until I added a checkbox to switch the data for the map. I wrote it like this for the view:

<input type="checkbox" name="switch" class="switch-checkbox"onclick="change();" checked>

For the function in js :

function change()
{
    var map = L.map('map').setView([37.8, -96], 4);

    L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        maxZoom: 18
    }).addTo(map);

    if (document.querySelector('.onoffswitch-checkbox').checked) {
        data = statesData;
        L.geoJson(statesData).addTo(map);
    } else {
        L.geoJson(statesDataTwo).addTo(map);
    }

Then I got an error that the map is already initialized. I tried to add map.remove(); before adding the new map. Like suggested here. But map is undefined. What is the way to do that? Thanks

Was it helpful?

Solution

Why are you adding new map? You probably have it already in global variable map, which is initialized on load. Work with this and change only layers on change/click. Something like this:

var map = L.map('map').setView([37.8, -96], 4);
L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    maxZoom: 18
}).addTo(map);

var geojsonLayers = {
    'states': L.geoJson(statesData),
    'statesTwo': L.geoJson(statesDataTwo)
};

function change()
{
    if (document.querySelector('.onoffswitch-checkbox').checked) {
        map.addLayer(geojsonLayers.states);
        if (map.hasLayer(geojsonLayers.statesTwo)) {
            map.removeLayer(geojsonLayers.statesTwo);
        }
    } else {
        map.addLayer(geojsonLayers.statesTwo);
        if (map.hasLayer(geojsonLayers.states)) {
            map.removeLayer(geojsonLayers.states);
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top