resizing a google map to fit a group of markers

google-maps-api-3

Solution

You can create a function like

function setBounds() {

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

As simple as that!

Problem

I'm using the V3 version of google maps, and wondered how to go about this-- I have an array of `google.maps.Markers` with their `LatLng` positions set. I would like to loop through the array and find the min/max latitude and longitude values of the markers, and center and resize the map so all the markers fit on the screen, with a small fudge factor. Looping through the markers array I can handle, but I'm not sure of how go about centering and resizing the map to fit them all (with a small border region surrounding, so no markers are flush against an edge.) I'm not sure if this helps or matters but the `<div>` the map lives in is 320x200 pixels.

Original source