Leaflet maxBounds - 边界不起作用

时间:2015-03-22 07:25:47

标签: javascript html css leaflet

我用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示例那样工作?

2 个答案:

答案 0 :(得分:7)

这是(我的)最终代码。

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);

答案 1 :(得分:3)

你必须使用边界作为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);