Leaflet maxBounds - 边界不起作用

Leaflet maxBounds - bounds do not work

我用 example code I found at Mapbox 试用了 Leafletjs maxBounds。

下面是我的完整代码,也在 jsfiddle here.

<!DOCTYPE HTML>
<html>
<head>
    <title>map - leaflet test bounds</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, minimal-ui" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge">

        <!-- leafletjs -->
        <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css" />
        <script src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>

        <style>
            body {
                margin: 0;
                padding: 0;
            }
            html, body, #map {
                height: 100%;
                width: 100%;
            }
        </style>
</head>

<body>
    <div id="map">
        <script>

            var southWest = L.latLng(40.712, -74.227),
                northEast = L.latLng(40.774, -74.125),
                mybounds = L.latLngBounds(southWest, northEast);

            var map = L.map('map').setView([40.743, -74.176], 17);
            L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png' , {
                maxBounds: mybounds,
                maxZoom: 18,
                minZoom: 16,
                attribution: '&copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors'
            }) .addTo(map);

            L.marker([40.743, -74.176]) .addTo(map);

        </script>
    </div>        
</body>

jsfiddle 结果看起来很奇怪,我不知道为什么。

为什么上面的代码不像 Mapbox 示例那样工作?

您必须使用 bounds 作为 L.tileLayer 的选项,而不是 maxBounds。

Bounds reference

此外,您似乎在 JSFiddle 中为 leaflet.css 加载了错误的文件,正确的来源是:http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css

最后,避免在 JSFiddle 中使用百分比尺寸,而是使用像素尺寸。 这是一个有效的 JSFiddle:http://jsfiddle.net/1zyL4q4a/4/

 L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png' , {
            bounds: mybounds,
            maxZoom: 18,
            minZoom: 16,
            attribution: '&copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors'
  }).addTo(map);

这是(我的)最终代码。

var map = L.map('map', {
    maxZoom: 18,
    minZoom: 16,
    maxBounds: [
        //south west
        [40.712, -74.227],
        //north east
        [40.774, -74.125]
        ], 
}).setView([40.743, -74.176], 17);

L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors'
}) .addTo(map);

L.marker([40.743, -74.176]) .addTo(map);

除非我误会了您在第一个示例中遵循的示例不是传单地图,否则 api 提供程序是 mapbox。赠品位于您遵循的第一个示例的顶部 html 脚本链接中。另一个是使用第一个示例中的代码时我的传单地图的异常行为。

正确的答案提供者使用传单API,如

所示

L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', { 界限:我的界限, 最大缩放:18, 最小缩放:16, attribution: '© OpenStreetMap 贡献者' }).addTo(地图);