Google Maps API Tutorial

© 2006, 2007, 2008, 2009 Mike Williams

 
Translate this page:

 

Associative arrays and Custom Icons

When I want to manage custom icons with information from XML data, I like to use an associative array.

Javascipt associative arrays can be used just like ordinary arrays, except that they use a string instead of a number as the index.

This means that you can store a meaningful name for the icon type in the XML data, rather than a meaningless number, without having to have a string of if statements to translate the XML attribute into the corresponding GIcon variable name.

E.g. if you've got custom icons that represent a house, a school and a factory, you can create an array like this

   var gicons=[];
   gicons["house"] = new GIcon( ... );
   gicons["school"] = new GIcon( ... );
   gicons["factory"] = new GIcon( ... );
and then create your markers like
   new GMarker(point, gmarkers["school"]);
and if you add an attribute to your XML, like icontype="school" you can read that attribute string from your XML in the normal way, and use it to index the associative array.
   new GMarker(point, gicons[icontype]);
Here's an example

You can see the XML data file that I used here

Potential Pitfalls

  1. Associative arrays are case specific. gicons["house"] is not the same as gicons["House"].

Back to Mike's Homepage
Up to the start of this tutorial