Question

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);
Was it helpful?

Solution

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 ); 

OTHER TIPS

if the above answer doesn't work for you (it didn't for me), the problem might lie in bootstrap (assuming you're using it). bootstrap modals specifically generate all sorts of wonky behaviour when i embed a map object in it.. curiously correcting itself if/when i drop an 'alert' in there.. in any case, i solved all my problems by just building my own modal (ie, not using bootstraps modals).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top