Zoom To Fit All Markers on Google Maps API v3

I’d like a problem that for once hasn’t already been solved by someone else.

I had a set of markers which needed to be all on screen, and for some reason there’s no .zoomToShow method. Fortunately it’s pretty simple to create yourself.

//  Make an array of the LatLng's of the markers you want to show
var LatLngList = array (new google.maps.LatLng (52.537,-2.061), new google.maps.LatLng (52.564,-2.017));
//  Create a new viewpoint bound
var bounds = new google.maps.LatLngBounds ();
//  Go through each...
for (var i = 0, LtLgLen = LatLngList.length; i < LtLgLen; i++) {
  //  And increase the bounds to take this point
  bounds.extend (LatLngList[i]);
}
//  Fit these bounds to the map
map.fitBounds (bounds);

And that’s pretty much it. Then, of course, I found that someone had already done this before, but for version two of the API.

19 thoughts on “Zoom To Fit All Markers on Google Maps API v3

  1. Just wanted to send you a quick thanks for this little snippet. My version which was much longer stopped working in version 3 — this one is much simpler.

  2. Do you know of a way to zoom to fit all markers while keeping the center of the map at a certain lat/long or marker?

  3. .count is not a valid javascript property. Please update your code to use the .length property.

    As matt said, change LatLngList.count() to be LatLngList.length

    Note: it’s a property, not a method, so leave out the parens ().

  4. Pingback: Dibujando rutas en Google Maps | Scipion Strikes Back

  5. If you have a list of markers and want to zoom and center them on screen, you can also keep extending bounds object while adding markers to list. So when you want to center map, you will not need to loop all markers again. Good luck

    var fMapBounds = new google.maps.LatLngBounds();
    function PlotMarker(Position) { //add a marker to map
    var latlng = new google.maps.LatLng(Position.Longitude);
    var googMarker = new google.maps.Marker({
    position: latlng,
    map: map,
    });
    fMapBounds.extend();
    return googMarker;
    }

    function CenterMap() { //just fit it
    if (fMapBounds!= undefined) {
    map.fitBounds(fMapBounds);
    }
    }