我在传单地图上有3层,它们是否根据缩放级别显示。
我只想设置 3个可能的缩放级别:例如,当用户单击按钮进行放大时,它将从缩放 1 变为缩放 4 (不进行缩放2和3)
有可能吗?
答案 0 :(得分:2)
限制缩放级别的一种方法是覆盖地图上的setView
方法,该方法用于处理缩放级别的所有更改。当检测到通过的覆盖无效时,覆盖将设置授权的缩放级别。
例如,
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);
}
还有一个演示
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>