Reputation: 16309
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.
Upvotes: 7
Views: 3547
Reputation: 161384
See the google.maps.Map fitBounds method
Add all the positions of your markers to an empty google.maps.LatLngBounds object, then call fitBounds on it.
var bounds = new google.maps.LatLngBounds();
for (var i=0; i < yourArrayOfMarkers.length; i++) {
bounds.extend(yourArrayOfMarkers[i].getPosition();
}
yourMap.fitBounds(bounds);
Upvotes: 5
Reputation: 22491
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!
Upvotes: 13