Leaflet.js - Fit geoJSON co-ordinates on map view

James picture James · Apr 20, 2012 · Viewed 15.7k times · Source

I have a leaflet.js map that has points and linestrings on it that come from an external JSON file.

If I add: map.setView(new L.LatLng(0,0), 10);

It will centre the map on the latitude and longitude 0,0. How can I set it so the map centre and zoom fit all of the points from the JSON on it?

Answer

Jason picture Jason · Apr 20, 2012

You could add all of your layers to a FeatureGroup which has a getBounds method. So you should be able to just say myMap.fitBounds(myFeatureGroup.getBounds());

The getBounds method for L.FeatureGroup is only available in the master branch (not the latest version, 0.3.1), for now at least.