Skip to content

Instantly share code, notes, and snippets.

@cccruzr cccruzr/.block
Last active Jun 23, 2017

Embed
What would you like to do?
Leaflet change tile service on zoom
license: mit

Example on how to change the tiles of basemap on zoom event. Check the console to check the current zoom level.

Built with blockbuilder.org

<!DOCTYPE html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.0.3/dist/leaflet.css" />
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
#mapid { height: 100%; }
</style>
</head>
<body>
<div id="mapid"></div>
<script src="https://unpkg.com/leaflet@1.0.3/dist/leaflet.js"></script>
<script>
var mymap = L.map('mapid').setView([4, -74], 5);
var cartoLight = L.tileLayer('http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png', {
attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> &copy; <a href="http://cartodb.com/attributions">CartoDB</a>',
subdomains: 'abcd',
maxZoom: 19
});
var cartoDark = L.tileLayer('http://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png', {
attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> &copy; <a href="http://cartodb.com/attributions">CartoDB</a>',
subdomains: 'abcd',
maxZoom: 19
});
cartoLight.addTo(mymap); //initial layer according to initial zoom
mymap.on("zoomend", function(e){
console.log("Zoom level: ", mymap.getZoom());
if(mymap.getZoom() > 6){ //Level 6 is the treshold
mymap.removeLayer(cartoLight);
cartoDark.addTo(mymap);
}else{
mymap.removeLayer(cartoDark);
cartoLight.addTo(mymap);
}
});
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.