How to reload Google Map in Bootstrap jQuery Tab

Adam Robertson picture Adam Robertson · Jul 3, 2014 · Viewed 7.3k times · Source

I'm using gmaps.js to load 2 maps in Bootstrap tabs. What happens, is the first map loads fine, but when the second tab (hidden) is clicked, the map doesn't load properly. After extensive Googling, I realize that this has to do with the Google map needing to be resized upon the click of the tab, as Google maps don't play nicely with hidden tabs. However, after trying many things, I just can't get it to work. Here's my fiddle: http://jsfiddle.net/7PueE/

/**
  * Fort Collins Map
  */
$(document).ready(function () {
map = new GMaps({
  div: '#fort-collins-map',
  lat: 40.574859,
  lng: -105.056756,
  width: '100%',
          height: '500px',
          scrollwheel: false,
    });
    map.addMarker({
      lat: 40.574859,
      lng: -105.056756,
      title: 'Fort Collins Office',
              infoWindow: {
                content: '<div class="bubble-wrap"><p class="office">Fort Collins Office</p><p>1120 E. Elizabeth St.</p><p>Suite F-101</p><p>Fort Collins, CO 80524</p><a href="https://www.google.com/maps/dir//1120+E+Elizabeth+St,+Fort+Collins,+CO+80524/@40.5748591,-105.0567559,17z/data=!4m13!1m4!3m3!1s0x87694ae0b3695899:0x5510539035305077!2s1120+E+Elizabeth+St!3b1!4m7!1m0!1m5!1m1!1s0x87694ae0b3695899:0x5510539035305077!2m2!1d-105.0567559!2d40.5748591">Directions</a></div>'
              }
    });
});
/**
  * Loveland Map
  */
$(document).ready(function () {
map = new GMaps({
  div: '#loveland-map',
  lat: 40.431917,
  lng: -105.078848,
  width: '100%',
          height: '500px',
          scrollwheel: false,
    });
    map.addMarker({
      lat: 40.431917,
      lng: -105.078848,
      title: 'Loveland Office',
              infoWindow: {
                content: '<div class="bubble-wrap"><p class="office">Loveland Office</p><p>3820 N. Grant Ave.</p><p>Loveland, CO 80538</p><a href="https://www.google.com/maps/dir//3820+N+Grant+Ave,+Loveland,+CO+80538/@40.4319173,-105.0788668,17z/data=!4m13!1m4!3m3!1s0x8769528a066dd4ad:0x2b893ca80de0bd33!2s3820+N+Grant+Ave!3b1!4m7!1m0!1m5!1m1!1s0x8769528a066dd4ad:0x2b893ca80de0bd33!2m2!1d-105.0788668!2d40.4319173">Directions</a></div>'
              }
    });
});

Answer

Dr.Molle picture Dr.Molle · Jul 3, 2014

trigger the resize-event of the window when a tab is shown(shown fires later than click, when the tab is already visible):

$('.nav-tabs').on('shown.bs.tab', function () {
    google.maps.event.trigger(window, 'resize', {});
});

http://jsfiddle.net/BAm69/