How to Load and Unload Google Maps Without Using the BODY Tag
July 6, 2007
I recently ran into a situation where I wanted to display a google map on a single page of a CMS website. The CMS uses a standard header for all pages which renders an identical BODY tag for all pages of the site.
Since the google map is only present on one page of the site, including the gmap onload and onunload event handlers in the body tag on every page is not practical or desirable (the functions being called are absent and throw javascript errors on non-map pages). Unfortunately, all of the google maps API examples use the body tag to attach functions to these events.
Simon Willison offers a solution that works across IE and Firefox (and others too probably, but I only tested in FF/IE). The following code can be placed anywhere after the gmaps load function definition:
// BEGIN NEW CODE TO AVOID USING BODY TAG FOR LOAD/UNLOAD
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
addLoadEvent(load);
// arrange for our onunload handler to 'listen' for onunload events
if (window.attachEvent) {
window.attachEvent("onunload", function() {
GUnload(); // Internet Explorer
});
} else {
window.addEventListener("unload", function() {
GUnload(); // Firefox and standard browsers
}, false);
}
// END NEW CODE TO AVOID USING BODY TAG FOR LOAD/UNLOAD













Posted in



June 23rd, 2008 at 11:09 am
This was helpful. I am also working on a Google Maps project in a CMS and cannot modify the body tag. Thank you!
Now if I can just figure out my other problems with this project….