I have a bunch or markers, and I want to show only the area containing them. I found a long list of similar questions (see at the bottom of the post for some), but none of the solutions works for me. The LatLngBounds is built correctly, but when I call fitBounds the result will be the following:
Instead of:
Can anybody spot an evident error in my code?
var opt = {
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"),opt);
var box = new google.maps.LatLngBounds();
for(var i=0;i<list.length;i++){
var p = new google.maps.LatLng(list[i].lat,list[i].lon);
var marker = new google.maps.Marker({
position: p,
map: map
});
box.extend(p);
}
map.fitBounds(box);
map.panToBounds(box);
我阅读和尝试过的一些帖子(列表不全面):
- Google 地图 v3 - 自动缩放级别? https://stackoverflow.com/questions/3245564/google-maps-v3-automating-zoom-level
- 谷歌地图V3自定义标记图像和fitBounds() https://stackoverflow.com/questions/10676140/google-maps-v3-custom-marker-images-and-fitbounds
- 带 fitBounds 的 Google 地图无法缩放 https://stackoverflow.com/questions/8565539/google-maps-with-fitbounds-dont-zoom
- Google 地图 api V3 中的 fitbounds() 不适合边界 https://stackoverflow.com/questions/2494756/fitbounds-in-google-maps-api-v3-does-not-fit-bounds
Edit: this actually happens if (as I do in my application) the map is at first hidden, and showed only later.
I hide it in this way:
$('#map').hide();
并显示它:
$('#map').show(function(){
//this is necessary because otherwise
//the map will show up in the upper left corner
//until a window resize takes place
google.maps.event.trigger(map, 'resize');
});
关于为什么会发生这种情况以及如何防止这种情况的任何线索(除了首次显示时初始化地图之外)?
顺便说一句,如果我在声明地图对象时设置缩放和居中(即我不使用fitBounds()
)那么即使在隐藏/显示之后,地图也会正确显示。
不过,我无法设置缩放和居中,因为点列表是在其他地方检索的,而且我事先不知道它们在哪里。