[GIS] Dynamically set zoom level based on a bounding box

leaflet

I have a leaflet map whose size depends on the size of the browser window. I would like the zoom level to be dynamically chosen so that it is as zoomed in as possible while showing the entirety of the bounding box.

Right now, I just have the zoom level hardcoded and the center point based on an average of points.

map = new L.Map('map', {
  center: new L.LatLng(
    latitudeSum/locations.length,
    longitudeSum/locations.length
  )
  zoom: 9
})

Instead, I'd like to give it a bounding box (two islands) and have the zoom level chosen based on the size of the window.

Best Answer

You could simply use:

var group = new L.featureGroup([marker1, marker2, marker3]);

map.fitBounds(group.getBounds());