fitBounds() shows whole earth (if map is first hidden and then shown)
Asked Answered
C

5

9

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: after calling fitBounds() Instead of: what should be 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):


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.

Cheju answered 19/6, 2012 at 10:1 Comment(3)
Probably, some of your list[i] elements are 'invalid'. Try to debug, and see, are all list[i] elements have 'lat','lon' properties, and those are not null,undefined,NaN, etc..Nodose
@Nodose thanks for the comment, but the elements are all good. As a side note, this happens with Firefox 13, Chrome 19 and IE 9.Cheju
Please provide the list you are iterating over. It will make it much easier to debug.Lecithinase
C
13

Solved (not in a nice way, though). What I ended up doing was initialising the LatLngBounds with the points when loading the page, but panning and zooming only when showing the map. In this way it works correctly. E.g.

var box;
function init(){
  var opt = {
      zoom: 8,
      mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById("map"),opt);
  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);
  }
}

and then, later (click on a button for example)

function showMap(){
  $('#map').show(function(){
    google.maps.event.trigger(map, 'resize');
    map.fitBounds(box);
    map.panToBounds(box);
  });
}

It works, but I don't like to have that global var hanging around. I implement the exact same behavior using OpenLayers, and it works correctly without the need for this hack. If anybody has a better solution, please post it and I will accept it if it works.

Thanks to @Engineer and @Matt Handy for helping me eliminate one possible source of errors.

Cheju answered 22/6, 2012 at 9:30 Comment(3)
Almost a year later and I hit this same problem! It seems that calling fitBounds() on a hidden map and then subsequently triggering resize event causes the problem. Your solution works as expected if I call fitBounds() after triggering the event when the map is visible. Cheers!Abdominous
Your description of the problem fit with a similar issue I had, and so did the solution. Thanks for pinning this down!Erin
This issue was nearly identical to something encountered using bootstrap tabs when the UI state was not visible by default. This works like a champ when extending the boundaries on a map from a hidden state.Douglasdouglashome
P
1

I tried your code in a fiddle, and it works as expected.

So the reason why your code fails must be in the definition of your datapoints (as already suggested by Engineer). Compare your list definition with mine and check if they are different.

Potency answered 19/6, 2012 at 13:34 Comment(1)
I tried your fiddle with my data, and it works. :( That must mean the error lies somewhere else in code. I'll try to strip it off to the bare minimum and see where it starts to work.Cheju
B
0

Modify to your needs

map.fitBounds(bounds);

var listener = google.maps.event.addListener(map, "idle", function() { 
  if (map.getZoom() > 16) map.setZoom(16); 
  google.maps.event.removeListener(listener); 
});
Botticelli answered 19/6, 2012 at 12:58 Comment(0)
B
0

same problem, found the reason is that I hide the map (make the container of the map display: none;) before calling fitbounds()

Bengaline answered 14/3, 2019 at 18:14 Comment(0)
A
0

To expand a bit on @JayThakkar 's answer, this worked for me

google.maps.event.addListenerOnce(map, 'idle', function(){
    map.fitBounds(bounds);
});

The addListenerOnce function removes the need to call google.maps.event.removeListener(listener);. And calling map.fitBounds(bounds) inside the listener let us use the calculated bounds's zoom level.

Alienee answered 7/10, 2020 at 10:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.