Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postpone google maps initialisation until after bootstrap tab is shown

I've researched a lot and it seems like a lot of people have had the same issue as me here, but i cant figure out how to fix it.

Basically i'm initializing a google map inside a hidden bootstrap tab. When i click on the pill to make the tab visible, only a small section of the map is shown.

From what i gather this is because the map is being initialized in a hidden element. So i need to initisialise the map only after the tab becomes visible.

I've tried and i've tried and i cant get the code right. Any help would be grand - how do i cause the map to only be executed after the tab is visible?

Thanks in advance

<!-- this is the hidden tab-->
<div class="tab-pane map-pane" id="map<?php echo $country_slug; ?>">

<div class = "row">
    <div class = "col-md-12">
      <div id="map-canvas" class = "map-canvas"></div>
    </div>
    </div>

    <!--and here is the map which executes inside the hidden tab-->
    <!--how can i cause this script to delay execution until the tab is shown?-->
<script type="text/javascript">

function initialize() {
    var mapOptions = {
       center: new google.maps.LatLng(22.39813,114.10943),
       zoom: 8
    };
        var map = new google.maps.Map(document.getElementById("map-canvas"),
    mapOptions);

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

like image 532
user1917727 Avatar asked Apr 10 '26 13:04

user1917727


2 Answers

http://bootply.com/102479

Add an id to your map tab link so it's easier to identify. Trigger a map resize event when the corresponding tab content is shown.

This way the map is only initialized once, which is not the case with the previous answer.

Note that you need to define the map variable outside of the initialize function.

like image 110
MrUpsidown Avatar answered Apr 13 '26 08:04

MrUpsidown


You should be able to attach a handler to the Bootstrap tab show event..

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

Working demo: http://bootply.com/102241

like image 38
Zim Avatar answered Apr 13 '26 08:04

Zim