Essential Web Concepts Blog

Tips & Resources for Business Owners and Web Developers

If you’ve ever tried to put a Google Map inside a jQuery Accordion or Tab panel, you know that unless the map is in a panel/tab that is initially active, you’ll get some annoying problems with the map not displaying correctly (see link for example). This seems to be due to the fact that these blocks have

display: none;

set by jQuery. There are a few tutorials online about how to fix this issue for tabbed panels, but not as much info on getting it to work for accordions.

This post is a simple example of how to get rid of the map artifacts using the Google Maps Javascript API V3.

We’ll start with the example code for the accordion from the jQuery site. The map will be placed in the ‘mapCanvas’ div on the third tab. Rather than including a map like we normally would:

var latlng = new google.maps.LatLng(32.334167, -95.3);
 
var myOptions = {
	zoom: 8,
	center: latlng,
	mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map($('#mapCanvas')[0], myOptions);

We’re going to bind the rendering of the map to happen after the first time the third tab is opened. The relevant code looks like:

var map = null;
var latlng = new google.maps.LatLng(32.334167, -95.3);
function initializeMap() {
	var myOptions = {
		zoom: 8,
		center: latlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	return new google.maps.Map($('#mapCanvas')[0], myOptions);
}
 
$(document).ready(function() {
	$("#accordion").accordion();
 
	$("#accordion").bind('accordionchange', function(event, ui) {
		if (ui.newContent.attr('id') == 'tabThree' && !map)
		{
			map = initializeMap();
		}
	});
});

This example was tested in FF3.6, Chrome 10, Safari 5, and IE 8.

Download: Complete example code.
Correctly Rendered Google Map

,
Trackback

No comments yet Share your thoughts!

Sorry, comments closed.