The Basics

Google Maps API Tutorial

Onload function and external controls

If you’ve been following this tutorial, adding external controls that affect the map is straight forward. If, however, you made an initial decision to put all the API Javascript code into an onload function you’ll need to make some of your variables and function declarations global.

Any variables and functions that are declared local to the onload function cannot be accessed from click or mouseover events that occur on html elements outside the map.

Here’s an example of using external controls to change the zoom level of the map.

All the functions which are called from clicks and mouseovers on html elements need to be global. That just means that you need to place the function declarations outside the onload function, like this

    // This function zooms in or out
    function myzoom(a) {
      map.setZoom(map.getZoom() + a);
    }

    function onLoad() {
      ...

Similarly, any variables which are used by those global functions need to be global. That just means making the initial declaration of the variables before any function declarations, and then populating those global variables in your onload function. In this particular example, the myzoom() function needs to use the “map” variable, and the myclick() function which handles the sidebar needs to access the gmarkers[ ] and htmls[ ] arrays.

   <script type="text/javascript">
    var gmarkers = [];
    var htmls = [];
    var map;

    function myclick(i) {
    . . .

Potential Pitfalls

  1. Remember that “onload()” in all lower case behaves like a reserved word in Firefox. Use a different name or change the capitalisation.
  2. Clicks and mouseovers in the html inside an info window are “external” events. Any functions or variables they use also need to be global.
  3. Don’t re-declare your variables inside the onload function. Make the onload function use the global variables rather than creating it’s own local variables with the same name. I.e. change the
            var map = new GMap(document.getElementById("map"));

    to

            map = new GMap(document.getElementById("map"));
  4. Beware free webhosting services that make their money by adding adverts to your pages. Some of them set their own onload function, using “window.onload”, which overwrites the onload setting in <body onload>.You may need to reset “window.onload” after their header code has executed, and then might be contractually obligated to call their olnload function as well as your own. The details vary depending on the webhosting service. Some of them go to considerable lengths to make this sort of thing very difficult because they don’t want people to be able to remove the adverts.
Advertisements