15

I'm trying to get a Google Map to appear in a vanilla Bootstrap tab. I built a fiddle taken directly from the Bootstrap docs, with the Gmap script pretty much exactly like Google recommends doing it too.

I am dumping the map object to console.dir and it has been initialized properly. In earlier projects I'd been able to display maps in tabs using the resize function-- but it doesn't seem to work with Bootstrap.

Has anyone gotten this working?

Here's the generic jsfiddle-- http://jsfiddle.net/B4zLe/4/

EDIT: adding code

JAVASCRIPT:

var map;

jQuery(function($) {
    $(document).ready(function() {
        var latlng = new google.maps.LatLng(-34.397, 150.644);
        var myOptions = {
            zoom: 8,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
        console.dir(map);
        google.maps.event.trigger(map, 'resize');

        $('a[href="#profile"]').on('shown', function(e) {
            google.maps.event.trigger(map, 'resize');
        });
    });
});

HTML:

<div>
<div class="bs-docs-example">
    <ul id="myTab" class="nav nav-tabs">
    <li class="active"><a href="#home" data-toggle="tab">Home</a></li>
    <li><a href="#profile" data-toggle="tab">Map</a></li>
</ul>
<div id="myTabContent" class="tab-content">
    <div class="tab-pane fade in active" id="home">
        <p>Raw denim you probably haven't heard of them jean shorts Austin. Nesciunt tofu stumptown aliqua, retro synth master cleanse. Mustache cliche tempor, williamsburg carles vegan helvetica. Reprehenderit butcher retro keffiyeh dreamcatcher synth. Cosby sweater eu banh mi, qui irure terry richardson ex squid. Aliquip placeat salvia cillum iphone. Seitan aliquip quis cardigan american apparel, butcher voluptate nisi qui.</p>
    </div>
    <div class="tab-pane fade" id="profile">
        <div id="map_canvas"></div>   
    </div>
</div>
julio
  • 6,630
  • 15
  • 60
  • 82

10 Answers10

30

Updated answer for Boostrap 3:

$("a[href='#my-tab']").on('shown.bs.tab', function(){
  google.maps.event.trigger(map, 'resize');
});

Note that you're selecting the link to the tab, not the tab itself.

apb
  • 3,270
  • 3
  • 29
  • 23
  • 6
    you need to keep the current center `var newmapcenter = map.getCenter(); google.maps.event.trigger(map, 'resize'); map.setCenter(newmapcenter);` – Shady Mohamed Sherif Nov 29 '15 at 22:49
  • 3
    This answer is the kind of answer that makes Stackoverflow awesome. Thank you @apb. The comment of @shady-sherif is also very useful as the map is decentered after the `resize` triggered event. – Maxooo Jan 22 '16 at 09:41
  • Thank 1000 times. – Jai Chauhan Sep 22 '17 at 11:44
21

dont use .tab-content > .tab-pane {display: none}
use this

.tab-content > .tab-pane {
    display: block;
    height:0;
    overflow:hidden;
}

.tab-content > .active {
    display: block;
    height:auto;
}
cevatasln
  • 355
  • 2
  • 3
10

Resize the map when tabs is shown

http://jsfiddle.net/B4zLe/49/

 $('#myTab a[href="#profile"]').on('shown', function(){
        google.maps.event.trigger(map, 'resize');
        map.setCenter(latlng);
 });
noocom
  • 101
  • 1
  • 3
  • How could this be also done for adding streetview map, in another TAB. I just cannot get it working. I tried, but with no success. http://jsfiddle.net/B4zLe/157/ – 422 Aug 06 '13 at 21:48
9

You're a little overoptimistic in how powerful the "resize" event is. From the documentation:

  • resize: Developers should trigger this event on the map when the div changes size: google.maps.event.trigger(map, 'resize')

In other words, resize won't do anything fancy like size the map to the window, but will only size it to the container it's in - in this case, the "map_canvas" div. However, this div has no dimensions, so the map has zero size.

Since you added some listeners to ensure that the map will change to the size of it's parent, this is a pretty easy fix - just add some code to modify the parent div to the desired size, and the map will resize to it. For example:

$("#map_canvas").css("width", 400).css("height", 400);

will size it to 400x400. Here's an example, you should be able to change it to whatever you'd like.

Bubbles
  • 3,795
  • 1
  • 24
  • 25
  • @Bubbles-- thanks! I understand how this works, but isn't the default behavior of a Google map to fit the container it's in? I guess I'm not sure how to handle a situation where the div is just 100%. – julio Nov 30 '12 at 17:47
  • 1
    It is, but the container has zero size in this case. I think this might be a bit of a chicken-or-the-egg problem - divs usually expand to fit the content (this depends on the styling rules, but we'll ignore the specifics), but in this case the content depends on the container for its position. So, the content looks to the container for sizing, finds zero size, and sets itself to that (and the container never expands since the content never does). You have to add some sort of sizing rules, even if it's just telling "map_canvas" to size itself to it's parent. – Bubbles Nov 30 '12 at 18:22
  • thanks-- I'm using `$("#map_canvas).wdith()` to get the width of the container, and set that as the width of the map-- but when I attempt to use `.height()` to get the height of the container, it returns nothing: http://jsfiddle.net/B4zLe/8/ -- Any thoughts? – julio Nov 30 '12 at 22:43
  • Well, it's the same problem - map_canvas is a container that has no height until it is specified or it's content gains a height (since it's a block element, it's width naturally goes to the max size it can fill). [Here's](http://jsfiddle.net/B4zLe/9/) a somewhat hacky workaround with css, but it may not be quite as flexible as you'd like. – Bubbles Nov 30 '12 at 23:48
2

I have the problem also with Google Maps with Bootstrap 3, but i solved the problem with tiny trick base on Andy B code :

 var cl=0;
 $("a[href='#maptab']").on('shown.bs.tab', function(){
     cl++;
     if(cl == 1){   // this is to prevent map initialized twice or more
         initialize();
     }
     else{
        //do nothing        
     }
 });

well.. atleast its work for me :)

Community
  • 1
  • 1
Myghty Draxx
  • 21
  • 1
  • 2
1

Absolutely wonderful solution by cevatasln. Me too I have used all possible jQuery and Javascript solutions, none worked! If you want to target specific tab and using dynamic gallery or something this will work for you

.tab-content > #tab5.tab-pane {
   display: block;
   height:0;
   max-height:0;
   overflow:hidden;
}

.tab-content > #tab5.active  {
   display: block;
   height:auto;
   max-height: 100%;
}
Hercules S.
  • 363
  • 3
  • 13
0
var map;

jQuery(function($) {
    $(document).ready(function() {
        var latlng = new google.maps.LatLng(-34.397, 150.644);
        var myOptions = {
            zoom: 8,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
        console.dir(map);
        google.maps.event.trigger(map, 'resize');

        $('a[href="#profile"]').on('shown', function(e) {
            google.maps.event.trigger(map, 'resize');
        });
        $("#map_canvas").css("height", 400);
    });
});

Fiddle

0

problem still persists in 2016, remove the google DOM handler and call the initialize() function with the jQuery "show" trigger as already written above. The map then is loaded on click on the TAB

google.maps.event.addDomListener(window, 'load', initialize);

jQuery('a[href="#googlemaps-tab-name"]').on('shown.bs.tab', function(e)
{   
    initialize();
});
nh-labs
  • 641
  • 7
  • 10
0

Still having problems with Bootstrap 3.3.7, jquery 1.11.3 and tabs. Everything works fine until you try to put map into tab that on load is first hidden. Then you get map loaded and everything should work, but you see only gray (or any other color, not sure) area of map. You can do everything there but you cannot see the map itself. On drag inside the map, you may be able to see SOME things, but in general - blank map.

Option 1 - you are able to see the map when you resize your window for a moment. But there is downfall as well - as soon as you change tab, it disapperas again.

Option 2 - you can put map on first tab and be done with it.

Option 3 - you can just make a code to "resize" the map (like shown previously). BUT there I ran into the problem - that does not ALWAYS work. At least it did not work for me:

.on("shown", function(){})
.on("shown.bs.tab", function(){});
.on("show.bs.tab", function(){});
...

Pretty much any variation did not work. I managed to make it work on FIRST time tab click by using link ID not href comparision, but as soon as I clicked on another tab and back again, gray map again ... I was like - seriously!?

Finally, I came up with solution: on that specific tab click (by id, I recommend), it makes all the necessary things. That means following - each time you click somewhere else (other links or tabs) and back to map tab, it will reload that map (and therefor may be slow a bit - depends on internet), but at least I got map, not empty gray image of google maps.

Hope that helps someone else in the future.

lohe
  • 109
  • 11
0

use below script

$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {

            init();

        });
Shridhar
  • 2,258
  • 2
  • 12
  • 13