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

前端 未结 5 1132
南笙
南笙 2021-02-15 06:50

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 s

5条回答
  •  一生所求
    2021-02-15 07:22

    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

    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.

提交回复
热议问题