MandalaTV
Personal and Professional Blog of Rich Hauck

Redrawing Google Maps with a Tabs Interface

by: Rich Hauck

On a recent project, I came across an apparent rendering bug with Google Maps when a maps is used in a tabbed menu/component.

When the map is placed in a hidden tab and is subsequently displayed, it only renders the top left tile of the map.

mapbug

After including v3 of the Google Maps API:

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true"></script>

Here’s what a basic map embed would look like, with a <div id=”mapcanvas”> containing the map:

var map;
var mapOptions = {
     zoom: 12,
     center: new google.maps.LatLng(40.2736, -76.8847),
     mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('mapcanvas'), mapOptions);

A lot of solutions online recommend triggering a Google Maps resize, which redraws the map when the browser has resized, like this:

$('.tab-container a').click(function (e) {
     google.maps.event.trigger(map, 'resize');
   });
});

This doesn’t take the map’s center and zoom into account during the redrawing, though. Here’s a simple way to address this:

$('.tab-container a').click(function (e) {
     resetMap(map);
});
function resetMap(m) {
     x = m.getZoom();
     c = m.getCenter();
     google.maps.event.trigger(m, 'resize');
     m.setZoom(x);
     m.setCenter(c);
   };
});

Make sure to pull the values for getZoom() and getCenter() before calling ‘resize’, otherwise, this won’t work.

I tried this with 3 different tabs systems: 

 I tried keeping these samples as simple as possible.

This resetMap() approached worked in all cases, however, I found that the whatever hidden container must have a css property of display:block, otherwise it doesn’t render properly. In the EasyTabs example, I found that this had to be reinforced on click().


2 thoughts on “Redrawing Google Maps with a Tabs Interface

  1. Thank you! This Blogpost and the Twitter’s Bootstrap Example helped me.

  2. resetMap() is awesome!

Leave a Reply

Your email address will not be published. Required fields are marked *

About Rich Hauck

Rich Hauck

I'm a creative technologist at Hauck Interactive, Inc. and an adjunct instructor at HACC. I live in Harrisburg, Pa. with my wife and three boys. I enjoy good coffee, Trappist beers, Orioles baseball, and good design.


Archives