Reputation: 3942
So I am trying to create a map-based visualization using leaflet.js. What I am trying to do is to use different GeoJSON files for different zoom levels of the map. For example when it is zoomed out, I would just like to display the state borders and when zoomed in, display county borders as well. I have the GeoJSON as a JavaScript variable in a .js
file which I load in the body. It works fine when I want to load only one .js
file, but when I dynamically want to change the .js
file based on the zoom level, I am unable to figure out how to dynamically make the other .js
file with the district GeoJSON data available.
The leaflet example I am referring to is this one. I looked into many SO questions dealing with dynamic .js
file loading, but to no avail.
Upvotes: 1
Views: 672
Reputation: 3942
I used the map.on()
property to achieve this. The code is as follows:
map.on('zoomend', function(e) {
if (map.getZoom() > 5) {
$.getScript('js/reassign_districts.js', function(data, textStatus, jqxhr) {
console.log(textStatus); // Success
console.log("Districts loaded.");
if (jqxhr.status == 200) {
map.removeLayer(geojson);
loadGeoJson();
}
});
} else if (map.getZoom() <= 5) {
$.getScript('js/reassign_states.js', function(data, textStatus, jqxhr) {
console.log(textStatus); // Success
console.log("States loaded.");
if (jqxhr.status == 200) {
map.removeLayer(geojson);
loadGeoJson();
}
});
}
});
Some of the variables and functions, though not defined here, make sense as far as their names are concerned.
Upvotes: 1