Zoom to fit all markers in Mapbox or Leaflet

AHOYAHOY picture AHOYAHOY · May 30, 2013 · Viewed 106.8k times · Source

How do I set view to see all markers on map in Mapbox or Leaflet? Like Google Maps API does with bounds?

E.g:

var latlngbounds = new google.maps.LatLngBounds();
for (var i = 0; i < latlng.length; i++) {
  latlngbounds.extend(latlng[i]);
}
map.fitBounds(latlngbounds);

Answer

L. Sanna picture L. Sanna · May 30, 2013
var group = new L.featureGroup([marker1, marker2, marker3]);

map.fitBounds(group.getBounds());

See the documentation for more info.