I\'ve created a quite complex store locator of sorts. The user enters their zip and a table returns results with corresponding markers on a map. They can page through result
I encountered this general problem today, thought I'd share a solution. I realise this is slightly different to your 'store locator' problem, but it does apply in many ways. In my case I have a collection of markers on the map and am adding one, and want to ensure all markers are now in view. This code checks each existing marker to see if its in the view, and along the way, builds a new bounding box that would contain them all, if required. At the end, if any have been found to not be in view, the view is reset so they all are.
(this uses Dojo's array module, simply a convenience wrapper around basic array iteration)
var origBounds = map.getBounds(),
newBounds = new google.maps.LatLngBounds(null),
anyFailed = false;
array.forEach(markers, function (m) {
newBounds.extend(m.position);
if (!origBounds.contains(m.position)) {
anyFailed = true;
}
});
if (anyFailed) {
map.setCenter(newBounds.getCenter());
map.fitBounds(newBounds);
}
One could easily modify this to only ensure the new marker is in view, by not looping and just doing a contains() check on the new marker.