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);
Some of the posts I read and tried (list not comprehensive):
- Google Maps v3 - Automating Zoom Level?
- Google maps V3 custom marker images and fitBounds()
- Google Maps with fitBounds don't zoom
- 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();
and show it:
$('#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');
});
Any clue as to why this happens and how to prevent it (apart from initialising the map when first shown)?
On a side note, if I set zoom and center when declaring the map object (i.e. I don't use fitBounds()
) then the map will show correctly, even after a hide/show.
I can't set zoom and center, though, because the list of points is retrieved elsewhere and I don't know where they are beforehand.
list[i]
elements are 'invalid'. Try to debug, and see, are alllist[i]
elements have 'lat','lon' properties, and those are notnull
,undefined
,NaN
, etc.. – Nodose