In most of the places the Google map is loaded on page load time. But if we want to display the map inside a jquery tab (initially hidden), we need not require to load the map on page load. This will reduce the page loading time. Another problem of loading the map on page load is the map will not appear properly inside the tab div. This is because, initially the div is hidden and the Google map requires height and width of the canvas div. In this code I will explain how to initialize Google map on tab click.

JavaScript Code:

<script type=”text/javascript”>
$(function(){
$(‘#tabs’).tabs();
$(‘#tabs’).bind(‘tabsshow’, function(event, ui) {
if (ui.panel.id == “tabs-2″) {
initialize();
}
});
});

function initialize() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById(“map_canvas”));
map.setCenter(new GLatLng(37.4419, -122.1419), 13);
map.setUIToDefault();
}
}
</script>

Html code:

<div id=”tabs”>
<ul>
<li><a href=”#tabs-1″>First</a></li>
<li><a href=”#tabs-2″>Second</a></li>
</ul>
<div id=”tabs-1″>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</div>
<div id=”tabs-2″><div id=”map_canvas” style=”width:200px; height:200px”></div></div>
</div>
Note:  If we are using animation to open the tab then we must use timeout function of 1 second  to initialize the function.
Code
setTimeout(function(){initialize();},1000);

Latest posts by rupak

  • Share/Bookmark