Adding/Removing GeoJSON layers using Leaflet

Try this instead:

function getJson(simp){  //Removed unneeded arguments here
    var url = 'file' + simp + '.json';
    map.removeLayer(geojsonLayer);
    //geojsonLayer.clearLayers();  I don't believe this needed.
    $.getJSON(url, function(data){
        geojsonLayer = L.geoJson(data, {
            style: defaultStyle,
            onEachFeature: onEachFeature
        });
        geojsonLayer.addTo(map);
    });
}

And for your calling function:

map.on('zoomend', function(e) {
    if (map.getZoom() >= 7 && map.getZoom() <= 10) {
        if (simpCounter == 0 || simpCounter == 2) {
        getJson(60);
        simpCounter = 1;
        }
    } else if (map.getZoom() >= 11) {
        if (simpCounter == 0 || simpCounter == 1) {
        getJson(35);
        simpCounter = 2;
        }
    } else if (map.getZoom() <= 7) { //Return to original data
        if (simpCounter == 1 || simpCounter == 2) {
        getJson(XX); //Fill out with correct file name
        simpCounter = 0;
        }
    }
});

When you are passing the arguments map, geojsonLayer and defaultStyle in the call getJson(defaultStyle, map, 60, geojsonLayer); you are creating new instances of the objects. You then perform work on the instances which may reflect on the screen but once it get back to the 'main loop' it basically forgets everything it just did and returns to the previous state.

Since I am guessing you defined defaultStyle, map, and the initial geojsonLayer population in the global scope you just have to call them, no need to pass them. With the adjustments I made it changes the global map so changes persist after function calls finish.

This solution worked for me. You can see the entire file contents I made here: http://pastebin.com/yMYQJ2jK

I also define a final zoom level for 1-7 so you can see you initial JSON data when you return to the initial zoom level, otherwise it is lost and is never called back unless you reload the page!


I wrote the below example to show how to remove multiples geoJSON layer.

///adding geoJSON data

          var myGeoJSON = L.geoJSON(myData, {

            onEachFeature: function (feature, layer) {
                layer.myTag = "myGeoJSON"
            }

        });


////// function to remove geoJSON layers 

    var removeMarkers = function() {
        map.eachLayer( function(layer) {

          if ( layer.myTag &&  layer.myTag === "myGeoJSON") {
            map.removeLayer(layer)
              }

            });

    }

//// calling function 

removeMarkers();

Tags:

Jquery

Leaflet