Google maps in hidden div

Rob picture Rob · Aug 16, 2011 · Viewed 18k times · Source

I have a page with two tabs. The first tab has photos and the second a google map. The problem is that the google map is not completely drawing because it is in a hidden div. So I moved the initialize() function to the href of the map tab using onclick(). This works the first time you click on it but when you return to the photos tab and then go back to the map tab the map only partially draws. If you click the map tab a second time it works perfectly. Any ideas?

tabs javascript:

<script type="text/javascript">

$(function () {
    var tabContainers = $('div.tabs > div');

    $('div.tabs ul.tabNavigation a').click(function () {
        tabContainers.hide().filter(this.hash).show();

        $('div.tabs ul.tabNavigation a').removeClass('selected');
        $(this).addClass('selected');

        return false;
    }).filter(':first').click();
});

</script>

google maps javascript:

<script type="text/javascript">
  function initialize() {
    var latlng = new google.maps.LatLng(<?=$lat ?>, <?=$lng ?>);
    var myOptions = {
      zoom: 15,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"),
        myOptions);

   var marker = new google.maps.Marker({
      position: latlng, 
      map: map, 
      title:"<?=$fulladdress ?>"
  });   
}
</script>

html:

<div class="tabs">
        <ul class="tabNavigation">
            <li><a href="#first">Photos</a></li>
            <li><a href="#map_canvas" onclick="initialize(); return false;">Map</a></li>
        </ul>


        <div id="first"> </div>
      <div id="map_canvas" ></div>

Answer

Doug Molineux picture Doug Molineux · Aug 16, 2011

I've seen this before you need to resize the map:

google.maps.event.trigger(map, 'resize');
map.setZoom( map.getZoom() );

This is for V3:

http://code.google.com/p/gmaps-api-issues/issues/detail?id=1448

A little more info:

https://groups.google.com/group/google-maps-js-api-v3/browse_thread/thread/251f20b769d116ea/ba3ca54f5e1352a2?pli=1