The problem is this: we set
var bounds = new google.maps.LatLngBounds();
so that we can later fit our markers to a bounded area on the map. GMaps will always zoom out asynchronously to fitBounds() accordingly, but will not zoom in to achieve the same (as previously noted by @broady). This is not ideal for many applications as once you have gone and displayed a series of markers on the map that caused the map to zoom out (maybe <10), it will not zoom back in without the user manually doing so.
GMaps will continue to use the bounds of the (lack of better words) most zoomed out marker collection status (sorry). Setting to 'null' before each call for new markers gives you a fresh map to work with.
To auto-zoom in, simply set the LatLngBounds(); to 'null' like so (see pseudo example below to see its placement):
bounds = new google.maps.LatLngBounds(null);
Pseudo example:
// map stuff/initiation
...
var bounds = new google.maps.LatLngBounds();
var gmarkers = [];
function CreateMarker (obj) {
myLatLng = new google.maps.LatLng(obj['latitude'], obj['longitude']);
marker = new google.maps.Marker({
position: myLatLng,
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(obj['job']);
infowindow.open(map, marker);
}
})(marker, i));
bounds.extend(myLatLng);
gmarkers.push(marker);
}
....
// here's an AJAX method I use to grab marker coords from a database:
$.ajax({
beforeSend: function() {
clear_markers(gmarkers); // see below for clear_markers() function declaration
},
cache: false,
data: params,
dataType: 'json',
timeout: 0,
type: 'POST',
url: '/map/get_markers.php?_=<?php echo md5(session_id() . time() . mt_rand(1,9999)); ?>',
success: function(data) {
if (data) {
if (data['count'] > 0) {
var obj;
var results = data['results'];
// Plot the markers
for (r in results) {
if (r < (data['count'])) {
CreateMarker(results[r]);
}
}
}
}
},
complete: function() {
map.fitBounds(bounds);
}
});
// clear_markers()
function clear_markers(a) {
if (a) {
for (i in a) {
a[i].setMap(null);
}
a.length = 0;
}
bounds = new google.maps.LatLngBounds(null); // this is where the magic happens; setting LatLngBounds to null resets the current bounds and allows the new call for zoom in/out to be made directly against the latest markers to be plotted on the map
}
panToBounds
is supposed to do withoutfitBounds
. – Bigamist