I am trying to show different GeoJSON layers at different zoom layers using the Leaflet API. I can load and display all three layers at once (though I do not actually want them all to show at once). I can load and display them at different zoom levels.
I have the code set up so that at Zoom levels 1-6, the map will show one GeoJSON layer. At levels 7-10, it will show another, and at levels 11+ it will show a third. Displaying them works. What I am trying to get working now is turning the others off if one is displayed. Going from 1-6 to 7-10 works (meaning that it turns off the 1-6 layer correctly), but not from 7-10 to 11+ (meaning that the 7-10 layer sticks around) and I cannot figure out why (it uses the same code).
Here is the ajax for the GeoJSON layers:
function getJson(defaultStyle, map, simp, geojsonLayer){
var url = 'file' + simp + '.json';
map.removeLayer(geojsonLayer);
geojsonLayer.clearLayers();
$.getJSON(url, function(data){
geojsonLayer = L.geoJson(data, {
style: defaultStyle,
onEachFeature: onEachFeature
});
geojsonLayer.addTo(map);
});
}
And here is the main function that calls the ajax depending on the zoom. simpCounter is set to 0 initially.
map.on('zoomend', function(e) {
if (map.getZoom() >= 7 && map.getZoom() <= 10) {
if (simpCounter == 0 || simpCounter == 2) {
getJson(defaultStyle, map, 60, geojsonLayer);
simpCounter = 1;
}
} else if (map.getZoom() >= 11) {
if (simpCounter == 0 || simpCounter == 1) {
getJson(defaultStyle, map, 35, geojsonLayer);
simpCounter = 2;
}
}
});
So again, the first transition turns off the old layer correctly, the but second transition does not.
Best Answer
Try this instead:
And for your calling function:
When you are passing the arguments
map
,geojsonLayer
anddefaultStyle
in the callgetJson(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 initialgeojsonLayer
population in the global scope you just have to call them, no need to pass them. With the adjustments I made it changes the globalmap
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!