Google Maps in Tabs

I was working on embedding 2 google maps on 2 tabs on a page, and came across a common problem. I want to document my solution, as many of the solutions I came across did not work for me.

I had a page with a tab for a US map, and a tab with an international map.

The problem was that When I clicked on the second tab (the international map), most of the map was grayed out, like this:
Screen Shot 2014-10-08 at 3.04.11 PM

I’d seen this problem on a few stackoverflow pages and blogs, with many suggested solutions. After trying several of them to no success, I made with work with simple solution.

Here is my original code (that didnt’ work):
The html with Bootstrap tabs:

And here is the Javascript using a JQuery google map plugin to do some cool clustering effects on the maps (details edited out and comments inserted):

The problem is that when you click on a new tab, the map object resizes for some reason, and does not resize correctly. The idea to fix this is to resize the map again when the tab is clicked, using JavaScript or some other event listener or something. Well, that didn’t work for me. What did work was to load the entire international map only when I clicked the tab, rather than using JQuery’s $(document).ready.

all I had to change was line 13 in the Javascript above from
jQuery(document).ready(function(e)
to
var loadInternationalMap = function() {

And then call that function when the tab was clicked (line 3 from the html above):

<a href="#international" role="tab" id="international-tab" onclick="loadInternationalMap();">International</a>

And viola, when I clicked on the international tab, the map loaded correctly.

I’m sure that this problem can be solved in many different ways depending on your particular situation, but the idea to to load (or resize, or re-initialize) the map once the tab is clicked, not just when the page is loaded.

Advertisements

About Aaron Glasenapp

I am a freelance Web/Rails developer and a hard core recreational mathematician.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: