Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show only United States when using Leaflet.js and 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);
like image 252
frajk Avatar asked Jan 23 '15 19:01

frajk


People also ask

Does leaflet use OpenStreetMap?

The Leaflet JavaScript. Our initial JavaScript is pretty straightforward. All we are doing here is creating the map and adding a tile layer. The tile images are coming from the OpenStreetMap servers which are good for testing.

How do you find the current location in a leaflet?

Show current user location The leaflet can also show the view based on the current location by using locate() method. It takes in an object that has setView property set to true and a maxZoom value set to a maximum value. This command will ask for the user's location and automatically set the view to that location.

Can leaflet use Vector tiles?

Leaflet doesn't support vector tiles by default. For basemaps, it is recommended to use it with traditional raster tiles (Mercator XYZ). Such tiles can be generated on demand for any of the GL styles with the open-source server software called TileServer GL.


1 Answers

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

like image 162
iH8 Avatar answered Sep 23 '22 15:09

iH8