問題描述
我正在使用 Leaflet.js 和 OSM 圖塊來創建地圖,但我只希望看到美國大陸,而不是整個世界.這可能嗎?
I'm using leaflet.js and OSM tiles to create a map, but I'd only like the continental United States to be viewable, not the entire world. Is that possible?
我正在像這樣加載地圖:
I'm loading the map like this:
var map = L.map('map').setView([39.82, -98.58], 5);
L.tileLayer('http://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png', {
attribution: '...',
maxZoom: 18
}).addTo(map);
推薦答案
這是可能的,而且很容易做到.首先,您需要美國大陸邊界框(最外邊緣)的坐標.你可以用谷歌搜索它們,我在這里找到它們:http://isithackday.com/geoplanet-explorer/index.php?woeid=24865672 您需要西南和東北坐標來創建邊界對象:
That's possible and easy to do. First of you'll need the coordinates for the bounding box (the outermost edges) of the continental united states. You can just google them, i found them here: http://isithackday.com/geoplanet-explorer/index.php?woeid=24865672 You need the southwest and northeast coordinates to create a bounds object:
var maxBounds = L.latLngBounds(
L.latLng(5.499550, -167.276413), //Southwest
L.latLng(83.162102, -52.233040) //Northeast
);
或者您可以使用簡寫版本,即嵌套數組:
Or you can go for the shorthand version, a nested array:
var maxBounds = [
[5.499550, -167.276413], //Southwest
[83.162102, -52.233040] //Northeast
];
現在您可以通過兩種方式在地圖上設置它們,初始化時,使用 maxBounds
選項和 L.Map
fitBounds 方法>
Now you can set those on your map in two ways, upon initialization, using the maxBounds
option and the fitBounds
method of L.Map
L.map('map', {
'center': [0, 0],
'zoom': 0
'maxBounds': maxBounds
}).fitBounds(maxBounds);
這是一個關于 Plunker 的工作示例:http://plnkr.co/edit/eEsxeh?p=預覽
Here's a working example on Plunker: http://plnkr.co/edit/eEsxeh?p=preview
或者當您的地圖已經初始化時,您可以使用 L.Map
的 setMaxBounds
方法和 fitBounds
方法.(假設您的地圖已分配給變量 map
):
Or when your map is already initialized you can use the setMaxBounds
method and the fitBounds
method of L.Map
. (assuming your map is assigned to variable map
):
map.setMaxBounds(maxBounds);
map.fitBounds(maxBounds);
這是一個關于 Plunker 的工作示例:http://plnkr.co/edit/HJKk0O?p=預覽
Here's a working example on Plunker: http://plnkr.co/edit/HJKk0O?p=preview
這篇關于使用 Leaflet.js 和 OSM 時僅顯示美國的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!