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

非 Y 不嫁゛ 提交于 2020-01-03 07:25:15

问题


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

回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/3873195/calling-map-fitbounds-multiple-times-in-google-maps-api-v3-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!