使用Leaflet.js和OSM时仅显示美国 [英] Show only United States when using Leaflet.js and OSM
问题描述
我正在使用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
];
现在,您可以在初始化时使用<$ c $以两种方式在地图上设置它们c> maxBounds 选项和 L.Map
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=preview
Here's a working example on Plunker: http://plnkr.co/edit/eEsxeh?p=preview
或者当你的map已初始化,您可以使用 setMaxBounds
方法和 L.Map的
。 (假设您的地图已分配给变量 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=preview
Here's a working example on Plunker: http://plnkr.co/edit/HJKk0O?p=preview
这篇关于使用Leaflet.js和OSM时仅显示美国的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!