Automatically adjust zoom to accommodate all marker in a google map

TrustyCoder picture TrustyCoder · Oct 9, 2010 · Viewed 42.6k times · Source

Using the latest version of Google maps. How to add markers using longitude and latitude and automatically adjust the zoom level of the map to include all the markers using JavaScript?

Answer

Salman A picture Salman A · Oct 11, 2010

Google Maps API v3 provides a LatLngBounds object to which you can add multiple LatLng objects. You can then pass this to Map.fitBounds() function as described here:

Partial Example

var latlng = [
    new google.maps.LatLng(1.23, 4.56),
    new google.maps.LatLng(7.89, 1.01),
    // ...
]; 
var latlngbounds = new google.maps.LatLngBounds();
for (var i = 0; i < latlng.length; i++) {
    latlngbounds.extend(latlng[i]);
}
map.fitBounds(latlngbounds);