Google Maps: Set Zoom to Fit All Markers

mapMarkerSeries

Zoom to fit a group of Markers

JsFiddle is a great tool to use for experiments with Google Maps. If you want to see the map displayed in the output frame, there are a few tweaks you need to know about

Note: Using Google Maps API V3

map options can be minimal:

var mapOptions = {
mapTypeId: google.maps.MapTypeId.ROADMAP
};

Use bounds global to hold outermost marker coordinates:

var bounds = new google.maps.LatLngBounds();

Put locations in an array “locationArray”. Iterate through them as you create markers so that each coordinate can be compared to bounds via bounds.extend in case it increases the size. Map.fitBounds(bounds) will set the zoom.

var coord;
for (coord in locationArray) {
var newMarker = new google.maps.Marker({
position: locationArray[coord],
map: map,
draggable: false
});
bounds.extend(locationArray[coord]);
markers.push(newMarker);
}
map.fitBounds(bounds);
}

Example:

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

Captcha loading...

This site uses Akismet to reduce spam. Learn how your comment data is processed.