Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling map.fitBounds() Multiple Times in Google Maps API v3.0

I've just begun using the Google Maps API (v3.0) and have had a good deal of success so far. I am loading a set of objects with Latitude & Longitude values from a database, passing them into my script, and looping over them in the script in order to add them to the map.

I am using the "bounds.extend() / map.fitBounds()" method of setting the map's zoom & bounds (see code below), which works as expected the first time around; however, if I clear out the existing markers, fetch another set of objects, and do the same thing on the same map instance, it sets the bounds incorrectly, usually resulting in a minimum zoom (an astronaut's view).

My suspicion is that my map object has some memory of the previous set of bounds that I've given it and that I need to find a way to clear these bounds before assigning my new ones, but I really can't be too sure.

Any help is greatly appreciated!

var locationList = [];
for (var i = 0; i < mapPoints.length; i++) { // mapPoints is a collection of DTOs
    var mapPoint = mapPoints[i];
    var location = new google.maps.LatLng(mapPoint.Latitude, mapPoint.Longitude);
    locationList.push(location);

    var marker = new google.maps.Marker({
        map: map,
        icon: '/Content/images/map/' + mapPoint.Status.Icon,
        shadow:  '/Content/images/map/shadow.png',
        position: location
    });
    markers.push(marker); // markers is an Array that is managed outside this loop
}

var bounds = new google.maps.LatLngBounds();
for (var j = 0; j < locationList.length; j++) 
    bounds.extend(locationList[j]);
map.fitBounds(bounds);
like image 739
egoodberry Avatar asked Oct 06 '10 13:10

egoodberry


1 Answers

This isn't the answer, so to speak, but a (slightly hacky) workaround that I discovered on a thread in the Google Maps Javascript API v3 group:

//map.fitBounds(bounds);
setTimeout( function() { map.fitBounds( bounds ); }, 1 ); 
like image 174
egoodberry Avatar answered Oct 18 '22 08:10

egoodberry