【发布时间】:2019-03-09 14:52:06
【问题描述】:
我在传单地图上有 3 个图层,它们根据缩放级别显示或不显示。
我只想设置 3 个可能的缩放级别:例如,当用户单击按钮进行放大时,它会从缩放 1 变为缩放 4(不经过缩放 2 和 3)
可以吗?
【问题讨论】:
-
您可以将
zoomend事件挂在地图上,如果它所在的缩放级别无效,则强制使用新的缩放级别。您需要跟踪缩放级别的移动方向。
标签: javascript leaflet
我在传单地图上有 3 个图层,它们根据缩放级别显示或不显示。
我只想设置 3 个可能的缩放级别:例如,当用户单击按钮进行放大时,它会从缩放 1 变为缩放 4(不经过缩放 2 和 3)
可以吗?
【问题讨论】:
zoomend 事件挂在地图上,如果它所在的缩放级别无效,则强制使用新的缩放级别。您需要跟踪缩放级别的移动方向。
标签: javascript leaflet
限制缩放级别的一种方法是覆盖地图上用于处理缩放级别的所有更改的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>
【讨论】: