最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Show only United States when using Leaflet.js and OSM - Stack Overflow

programmeradmin1浏览0评论

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/dark_all/{z}/{x}/{y}.png', {
    attribution: '...',
    maxZoom: 18
}).addTo(map);

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);
Share Improve this question edited Jan 23, 2015 at 19:44 frajk asked Jan 23, 2015 at 19:27 frajkfrajk 8631 gold badge6 silver badges14 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 17

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

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

Here's a working example on Plunker: http://plnkr.co/edit/eEsxeh?p=preview

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

Here's a working example on Plunker: http://plnkr.co/edit/HJKk0O?p=preview

发布评论

评论列表(0)

  1. 暂无评论