首页 > 解决方案 > 如何在 Leaflet 中设置一系列可能的缩放级别

问题描述

我在传单地图上有 3 个图层,它们根据缩放级别显示或不显示。

我只想设置3 个可能的缩放级别:例如,当用户单击按钮进行放大时,它会从缩放1变为缩放4(不经过缩放 2 和 3)

有可能吗?

标签: javascriptleaflet

解决方案


限制缩放级别的setView一种方法是覆盖地图上用于处理缩放级别的所有更改的方法。当检测到通过的缩放级别无效时,覆盖将设置授权缩放级别。

例如,

var map = L.map('map').setView([48.864, 2.345], 4);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <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: '&copy; <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>


推荐阅读