javascript - 如何在 Leaflet 中设置一系列可能的缩放级别
问题描述
我在传单地图上有 3 个图层,它们根据缩放级别显示或不显示。
我只想设置3 个可能的缩放级别:例如,当用户单击按钮进行放大时,它会从缩放1变为缩放4(不经过缩放 2 和 3)
有可能吗?
解决方案
限制缩放级别的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>
推荐阅读
- ios - 免费试用期后应用内购买一次性付款
- python - python pyserial 无法在 COM 端口建立与硬件的连接
- python - BadZipFile 仅在我使用变量时出错
- python - TensorFlow 的 QAT 似乎没有使用 AllValuesQuantizer 执行每通道量化
- firebase - 如何在 Firebase 中使用相同的电子邮件创建两个帐户
- c# - 如何在 C# 中快速搜索 word 和 Pdf 文档上的特定文本?
- cmake - 将 CLion 构建配置文件存储在存储库中
- c++ - NSString initWithBytesNoCopy 在使用 NSUTF32StringEncoding 编码时返回 nil
- javascript - 如何在 React 应用程序中为不同的页面使用自定义按钮和引导按钮?
- android - AppBarLayout 不会滚动到焦点 EditText