I have 3 layers on a leaflet map, they are displayed or not according to the zoom level.
I'd like to set only 3 possible zoom levels: for example, when a user clicks on the button to zoom in, it would go from zoom 1 to zoom 4 (without going through zoom 2 and 3)
Is it possible to do?
One way to restrict the zoom levels would be to override the setView method on your map that is used to handle all changes of zoom levels. The override would set an authorized zoom level when it detects that the one passed is invalid.
For example,
var map = L.map('map').setView([48.864, 2.345], 4);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
// allowed zoom levels
var allowZooms = [4, 8, 12];
map.setView = function(center, zoom, options) {
// tests if the requested zoom is allowed
if ((zoom) && (allowZooms.indexOf(zoom) === -1)) {
// this._zoom is an internal value used to reference the current zoom level
var ixCurZoom = allowZooms.indexOf(this._zoom);
// are we zooming in or out?
var dir = (zoom > this._zoom) ? 1 : -1;
// pick the previous/next zoom
if (allowZooms[ixCurZoom + dir]) {
zoom = allowZooms[ixCurZoom + dir];
} else {
// or abort the zoom if we're out of bounds
return this;
}
}
// call the parent method
return L.Map.prototype.setView.call(this, center, zoom, options);
}
And a demo
var map = L.map('map').setView([48.864, 2.345], 4);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
var allowZooms = [4, 8, 12];
map.setView = function(center, zoom, options) {
if ((zoom) && (allowZooms.indexOf(zoom) === -1)) {
var ixCurZoom = allowZooms.indexOf(this._zoom);
var dir = (zoom > this._zoom) ? 1 : -1;
if (allowZooms[ixCurZoom + dir]) {
zoom = allowZooms[ixCurZoom + dir];
} else {
return this;
}
}
return L.Map.prototype.setView.call(this, center, zoom, options);
}
html, body {
height: 100%;
margin: 0;
}
#map {
width: 100%;
height: 100%;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.3.4/leaflet.css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.3.4/leaflet.js"></script>
<div id='map'></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With