Google, Guns, Geekery

I’ve been fiddling around with the Google Maps API for a couple of days.  I got the idea that I could use it to display my DFW gun show listings on a map. 

Displaying a basic Google Map via the API is pretty simple.  You just import their Javascript library (you have to register for an API key for it to work, though) and use the various objects that they provide.  For a simple map, all you need to do is create a <div> in the HTML body of the page and associate the map object with it by name.  The map will take its size and location from the div.  Once you declare the map, you just have to center it on a point (by Lat/Long) to get it to display (I chose a location in Irving, since that’s fairly central to the D/FW area).

The map itself (as noted above) uses Lat/Long to display points and to place markers.  They provide a Geocoder object that allows you to get back a Lat/Long from an address.  Since the Geocoder has to call back to Google to do the lookup, and that can take some time, the interface is asynchronous.  So you have to provide a callback function to get the “point” object back and do something with it.  This function will create a marker with an “InfoWindow” (the little pop-up balloon that Google Maps uses) that contains HTML

However, getting to the point where you can create the markers requires a bit of care.  My choice to put my map creation code into an “onload” event caused me some grief at first until it got through my thick skull that I needed to gather all the addresses (and their associated shows) while the page was being created, then do the actual marker creation in the function.  Part of this was caused by the fact that I’m working with EE, where you have to use one of their weblog entry loops to cycle through the entries.  What I ended up doing was to create an array of “address” entries such that each one contained a list of shows for that entry.  As the weblog loop runs, it generates Javascript code that adds new entries to the array.  Finally, once the page is loaded, my other function gets invoked and cycles through the array, invoking the Geocoder, which in turn (eventually) invokes the marker creation function.

Finally, once the last marker is actually created, the code recenters and resizes the map to fit the markers.

The result is something like this:

It’s kind of interesting to watch, since the markers just kind of “pop in” and then the thing recenters/resizes.  Here’s the link.

1 Comment

  1. Very cool.  Would you send me the code for that?  I’d love to look at it to see how much of it I understood.  I find that kind of thing fascinating.