How to render Map inside jquery tabs on tab click
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(){
$(‘#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);
<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
- ECMAScript for XML: E4X - April 10th, 2012
- How to Theme profile2 module form - September 22nd, 2011
- Front-end page optimization - August 3rd, 2011
- Why we use Subversion (SVN) in web development - June 30th, 2011
Tags: HTML, javascript & jquery
