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….
August 29th, 2008 at 12:14 pm
Thanks for your info, but I just can’t get it to work. Do you have an example of the complete code somewhere so I can see how it all fits together? I’m messing up the script somewhere. Thanks.
September 23rd, 2008 at 8:28 am
Thanks dude! This worked like a charm.
October 16th, 2008 at 11:40 am
Super! Tu peux pas imaginer comment j’ai souffert pour ce truc! Je suis meme aller jusqu’à utiliser des IFRAME
You are a genius!
November 17th, 2008 at 2:24 am
can not work in IE8…
December 3rd, 2008 at 7:01 am
Thanks!
January 6th, 2009 at 6:18 pm
You’ve just saved me from the horror of ASP.NET master pages strangling my maps!
many thanks!
April 16th, 2009 at 12:35 am
OH MY GOD THANK YOU THIS ROCKS
May 5th, 2009 at 3:20 pm
Huge thanks for the code.