I have a map with multiple locations on it. The locations are determined at runtime depending on the page displayed (they are locations for our dealers, so they vary based on the dealer id. (The markers display fine, but now I want to center the map so that it is zoomed to include all of the markers and centered based on the markers displayed. How do I do this? Right now, the zoom and center are set manually. Here is my code so far:
<script type="text/javascript">
function initialize() {
var locations = [
<?php
$loc = '';
$i = 1;
foreach ($coordinates as $c) {
$loc .= '["' . $c->company . '", ' . $c->latitude . ', ' . $c->longitude . '], ';
$i++;
}
echo substr($loc, 0, -2);
?>
];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(-33.92, 151.25),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Create google.maps.LatLngBounds object, which contains all markers’ positions, and then use
fitBoundsmethod of google.maps.Map object: