Problems with Google Maps API v3 + jQuery UI Tabs

JqueryGoogle MapsJquery Ui-TabsGoogle Maps-Api-3

Jquery Problem Overview


There are a number of problems, which seem to be fairly well-known, when using the Google Maps API to render a map within a jQuery UI tab. I've seen SO questions posted about similar issues (here and here, for example) but the solutions there only seem to work for v2 of the Maps API. Other references I checked out are here and here, along with pretty much everything I could dig up through Googling.

I've been trying to stuff a map (using v3 of the API) into a jQuery tab with mixed results. I'm using the latest versions of everything (currently jQuery 1.3.2, jQuery UI 1.7.2, don't know about Maps).

This is the markup & javascript:

<body>
    <div id="dashtabs">
        <span class="logout">
            <a href="go away">Log out</a>
        </span>
        <!-- tabs -->
        <ul class="dashtabNavigation">
            <li><a href="#first_tab" >First</a></li>
            <li><a href="#second_tab" >Second</a></li>
            <li><a href="#map_tab" >Map</a></li>
        </ul>

        <!--  tab containers -->
        <div id="first_tab">This is my first tab</div>
        <div id="second_tab">This is my second tab</div>
        <div id="map_tab">
             <div id="map_canvas"></div>
        </div>
    </div>
</body>

and

$(document).ready(function() {
    var map = null;
    $('#dashtabs').tabs();
    $('#dashtabs').bind('tabsshow', function(event, ui) {
        if (ui.panel.id == 'map_tab' && !map)
        {
            map = initializeMap();
            google.maps.event.trigger(map, 'resize');
        }
    });
});

function initializeMap() {
    // Just some canned map for now
    var latlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {
        zoom: 8,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    return new google.maps.Map($('#map_canvas')[0], myOptions);
}

And here's what I've found that does/doesn't work (for Maps API v3):

  • Using the off-left technique as described in the jQuery UI Tabs documentation (and in the answers to the two questions I linked) doesn't work at all. In fact, the best-functioning code uses the CSS .ui-tabs .ui-tabs-hide { display: none; } instead.
  • The only way to get a map to display in a tab at all is to set the CSS width and height of #map_canvas to be absolute values. Changing the width and height to auto or 100% causes the map to not display at all, even if it's already been successfully rendered (using absolute width and height).
  • I couldn't find it documented anywhere outside of the Maps API, but map.checkResize() won't work anymore. Instead, you have to fire a resize event by calling google.maps.event.trigger(map, 'resize').
  • If the map is not initialized inside of a function bound to a tabsshow event, the map itself is rendered correctly but the controls are not - most are just plain missing.

So, here are my questions:

  • Does anyone else have experience accomplishing this same feat? If so, how did you figure out what would actually work, since the documented tricks don't work for Maps API v3?
  • What about loading tab content using Ajax as per the jQuery UI docs? I haven't had a chance to play around with it but my guess is that it's going to break Maps even more. What are the chances of getting it to work (or is it not worth trying)?
  • How do I make the map fill the largest possible area? I'd like it to fill the tab and adapt to page resizes, much in the way that it's done over at maps.google.com. But, as I said, I appear to be stuck with applying only absolute width and height CSS to the map div.

Sorry if this was long-winded but this might be the only documentation for Maps API v3 + jQuery tabs. Cheers!

Jquery Solutions


Solution 1 - Jquery

Note: this answer received an invalid 3rd party edit which essentially replaced its content, something that a 3rd party editor should not do. However, the result may be more useful than the original, so both versions are now given below:


  • Original author Anon's version from 2010, after one edit by Anon

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

is suggested by http://code.google.com/p/gmaps-api-issues/issues/detail?id=1448 as a v3 substitute for v2's checkResize().

Blech - bad google, no cookie.


  • User Eugeniusz Fizdejko's complete rewrite form 2012:

For me works when adding a marker:

var marker = new google.maps.Marker({
    position: myLatlng,
    title:"Hello World!"
});

google.maps.event.addListener(map, "idle", function(){
    marker.setMap(map);
});

Solution 2 - Jquery

Actually scratch my answer above. The jQueryUI website has the answer and here it is:

> Why does... > > ...my slider, Google Map, sIFR etc. > not work when placed in a hidden > (inactive) tab? > > Any component that requires some > dimensional computation for its > initialization won't work in a hidden > tab, because the tab panel itself is > hidden via display: none so that any > elements inside won't report their > actual width and height (0 in most > browsers). > > There's an easy workaround. Use the > off-left technique for hiding inactive > tab panels. E.g. in your style sheet > replace the rule for the class > selector ".ui-tabs .ui-tabs-hide" with

.ui-tabs .ui-tabs-hide {
    position: absolute;
    left: -10000px;
}

> For Google maps you can also resize > the map once the tab is displayed like > this:

$('#example').bind('tabsshow', function(event, ui) {
    if (ui.panel.id == "map-tab") {
        resizeMap();
    }
});

resizeMap() will call Google Maps' checkResize() on the particular map.

Solution 3 - Jquery

Just redefine the css class for hidden tab:

.ui-tabs .ui-tabs-hide {
	position: absolute !important;
	left: -10000px !important;
	display:block !important;
}

Solution 4 - Jquery

This is what you can do for Google Maps v3:

google.maps.event.addListenerOnce(map, 'idle', function() {
	google.maps.event.trigger(map, 'resize');
    map.setCenter(point); // be sure to reset the map center as well
});

Solution 5 - Jquery

I load the maps after the tab has been shown.

This is hacky but it worked for me. Simply store the url of the map iframe inside the iframes rel attribute like so:

<iframe width="490" height="300" rel="http://maps.google.com/maps?f=q&amp;source=s..."></iframe>
                       

This event will set the iframe src attribute to the url inside the rel.

        $("#tabs").tabs({
            show:function(event, ui) {
                var rel = $(ui.panel).find('iframe').attr('rel');
                $(ui.panel).find('iframe').attr('src',rel);
            }
        });

Solution 6 - Jquery

This doesn't answer all your questions, but I've gotten it working and all the other answers are missing one thing -- when you redraw the map with the "resize" event, you will lose the place the map was centered on. So you also need to update the center of the map again with setCenter, if your map is centered on a position.

Also, you don't want to initialize the map every time the tab change is triggered, as that is not efficient and can result in extra geocodes. First, you need to save your centered location, which can be a static lat/long, or if geocoding, may look something like this:

var address = "21 Jump St, New York, NY"; 
var geocoder = new google.maps.Geocoder();    
var myOptions = {
  zoom: 16,      
  mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

var center;

geocoder.geocode( { 'address': address}, function(results, status) {
  if (status == google.maps.GeocoderStatus.OK) {        
    center = results[0].geometry.location;
    map.setCenter(center);
    var marker = new google.maps.Marker({
        map: map, 
        position: results[0].geometry.location
    });
  } else {
    alert("Geocode was not successful for the following reason: " + status);
  }
});

Then

$("#tabs").tabs();

$('#tabs').bind('tabsshow', function(event, ui) {
    if (ui.panel.id == "mapTab") {
        google.maps.event.trigger(map, "resize");
        map.setCenter(center);	 // Important to add this!      
    }
});

Where 'mapTab' is the ID of your mapTab, and 'map' is the var name for your map object.

Solution 7 - Jquery

Be sure that the code that initializes your map is called BEFORE the snippet that initializes your tabs.

The only annoyances I had were that a click on the map tab made the browser jump to focus on the map and that it broke out of the default border that jQuery puts around the main tabs container. I added a return false onclick call to the map tab's a tag to handle the first and a simple border-size: 0 on the main tabs div to handle the second.

All of this worked for me.

Good luck!

Solution 8 - Jquery

I've been through every forum searching for the answer to this...they all said to use the

map.checkResize()

solution....nothing seemed to work...then I...why not initialize the tab when the tab is shown so i used this

$("#servicesSlider ").tabs({ 		
				//event: 'mouseover'
			fx: { height: 'toggle', opacity: 'toggle'},
			show: function(event, ui) {
				  if (ui.panel.id == "service5") {
					  $(ui.panel).css("height","100%")
    				initialize()
					}}
			});

"service5" is the id of my tab that holds my google map v3.

Hope this works for you!

Solution 9 - Jquery

I had this problem too, I was loading the maps through AJAX.

It seems the problem with percentage was to do with the panel not having any set size (the one containing the loaded markup).

Using the following code when creating the tabs helped me a lot:

$("#mainTabs").tabs({'show': function(event, ui){
  $(ui.panel).attr('style', 'width:100%;height:100%;');
  return true;
 }});

Solution 10 - Jquery

Hey guys, this code fixes the error but in IE not working. After searching and searching, I discovered that we must add the following line and everything works to perfection:

< !--[if IE]>
< style type="text/css">
.ui-tabs .ui-tabs-hide { position: relative; }
< /style>
< ![endif]-->

Solution 11 - Jquery

You can call

map.fitBounds(bounds)

that will do the refresh

Solution 12 - Jquery

Very irritating problem but with a bit of a hackaround it's fixable. The key is to make the position relative #tabs adjust to the outerheight of each of the tabs when you select a new one. Here's how I did it:

$('#tabs').tabs({
   selected:0,
   'select': function(event, ui) {
    //this is the href of the tab you're selecting
    var currentTab = $(ui.tab).attr('href');
    //this is the height of the related tab plus a figure on the end to account for padding...
    var currentInner = $(currentTab + '.detail-tab').outerHeight() + 40;
    //now just apply the height of the current tab you're selecting to the entire position:relative #tabs ID
    $('#tabs').css('height', currentInner);
   }
  });

here's the css i used:

#tabs { position: relative; }
/*set the width here to whatever your column width is*/
.ui-tabs-panel{ position:absolute;top:0px; left:0; width:575px;}
.ui-tabs-panel.ui-tabs-hide { display:block !important; position:absolute;  left:-99999em; top:-9999em}

Solution 13 - Jquery

I got this working easily by Asynchronously loading the API and then simply calling loadScript from the <a> tag tied to the relevant tab from the onclick event like so:

<li><a href="#tab3" onclick="loadScript();">Maps</a></li>

Solution 14 - Jquery

I had the same problem and none of the answers worked for me. Maybe I didn't know how to use them in my code so I added an onclick event to the tab menu to initialize Google map and it is working. I do not know if it is a good practice though.

jQuery(document).ready(function($) {
$( '#tabs' ).tabs();
var href = $('#tabs').find('a[href="#tabs-4"]');
(href).on('click',function(){
	initialize();
})});
var map;
function initialize() {
  var mapOptions = {
    zoom: 8,
    center: new google.maps.LatLng(-34.397, 150.644),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById('map'),
      mapOptions);
}

<div id="tabs-4">
	<div id="map" style="width:580px;height:380px;">
	</div>
</div>

Solution 15 - Jquery

Another solution for Maps API v3 (exp) and jQuery UI 1.10:

var pano = new google.maps.StreetViewPanorama(...);

$('#tabs').tabs({
  'activate': function(event, ui) {
    if (ui.newPanel[0].id == "maps-tabs-id") {
      pano.setVisible(true);
    }
  }
});

Solution 16 - Jquery

I did what Keith says and it works for me, in my case I'm using jQuery waypoints for my tabbed navigation, for better understanding here's the code I used:

In the HEAD

<head>

<!-- Google Maps -->
<script>
function initialize() {
  var mapOptions = {
    zoom: 8,
    center: new google.maps.LatLng(-34.397, 150.644)
  };

  var map = new google.maps.Map(document.getElementById('map_canvas'),
      mapOptions);
}

function loadScript() {
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp' + '&signed_in=true&callback=initialize';
  document.body.appendChild(script);
}
window.onload = loadScript;
</script>

</head>

Inside of my tabs:

<li><a href="#MyMap" onclick="loadScript();">My Map</a></li>

Then in the DIV

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

Hope this helps someone, thanks for all!

Solution 17 - Jquery

I was facing the same issue in Semantic UI, the problem was fixed while calling init(); function when a tab loads or you can bind it as well.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMatt BallView Question on Stackoverflow
Solution 1 - JqueryAnonView Answer on Stackoverflow
Solution 2 - JqueryjeffkeeView Answer on Stackoverflow
Solution 3 - JquerymemberyhView Answer on Stackoverflow
Solution 4 - JqueryjayarjoView Answer on Stackoverflow
Solution 5 - JqueryKeyoView Answer on Stackoverflow
Solution 6 - JquerypaulView Answer on Stackoverflow
Solution 7 - JqueryVaughnView Answer on Stackoverflow
Solution 8 - JqueryDaveView Answer on Stackoverflow
Solution 9 - JqueryAndyView Answer on Stackoverflow
Solution 10 - JqueryAndrés SepúlvedaView Answer on Stackoverflow
Solution 11 - JqueryJuan arceView Answer on Stackoverflow
Solution 12 - JqueryTom GordonView Answer on Stackoverflow
Solution 13 - Jquerykeithxm23View Answer on Stackoverflow
Solution 14 - Jqueryarjang27View Answer on Stackoverflow
Solution 15 - JqueryWernightView Answer on Stackoverflow
Solution 16 - JqueryyehannyView Answer on Stackoverflow
Solution 17 - JqueryMoxet KhanView Answer on Stackoverflow