2

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

1
  • Can you try to convert your issue into a jsFiddle? If you do that, it would be easier to help and while doing so there are chances that you might find the fix yourself.
    – bits
    Commented Feb 12, 2014 at 0:51

1 Answer 1

3

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);
        }
    }
}

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