How to Load and Unload Google Maps Without Using the BODY Tag

Date 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

9 Responses to “How to Load and Unload Google Maps Without Using the BODY Tag”

  1. Matt said:

    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….

  2. a said:

    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.

  3. iWolf said:

    Thanks dude! This worked like a charm.

  4. zwan said:

    Super! Tu peux pas imaginer comment j’ai souffert pour ce truc! Je suis meme aller jusqu’à utiliser des IFRAME :(
    You are a genius!

  5. fhmsha said:

    can not work in IE8…

  6. myxo said:

    Thanks!

  7. Ian Stalvies said:

    You’ve just saved me from the horror of ASP.NET master pages strangling my maps!

    many thanks!

  8. Ragnar said:

    OH MY GOD THANK YOU THIS ROCKS

  9. Emma Kane said:

    Huge thanks for the code.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>