Friday, December 17, 2010

Zoom to fit all markers with Google Maps V3


// creating the map
var map = new google.maps.Map(document.getElementById("map_canvas"), {
mapTypeId: google.maps.MapTypeId.ROADMAP
});

// latitude, longitude values
var latLons = [ { lat: 35.6453962, lon: 139.7117893 },
{ lat: 35.645076, lon: 139.709183 } ];

// this is the bounding box container
var bounds = new google.maps.LatLngBounds();

// iterating through the points
latLons.forEach( function (element, index, array) {

var point = new google.maps.LatLng(element.lat,element.lon);

// extending the bounding box
bounds.extend(point);

// creating the marker on the map
var marker = new google.maps.Marker({
position: point,
map: map
});
});

// zooming on the map
map.fitBounds(bounds);

2 comments: