Why is this page text-only?

« February 2007 | Main | April 2007 »

Building your first Google Map

Mashup seems to be the latest buzz word and Google Maps seems almost ubiquitous these days. While the challenge of using the Google Maps API may seem daunting, it's actually not nearly as difficult as you'd imagine. Having recently tackled my first one I thought I'd put together a quick step-by-step guide on how to setup the basics for anyone else who may be interested in doing the same.

Step 1 - Obtaining your Google Maps API Key
Point your browser to http://www.google.com/apis/maps/signup.html, fill out the form and get your free API key. You need this in order to make your mashup work online. Embed it into the head tag of you page like so:

<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=INSERT-KEY-HERE" type="text/javascript"></script>

Step 2 - Plotting your points
For the purposes of this example I'm picking a few of my favorite restaurants in Washington, DC. While you can easily hard-code these into the Google Maps javascript, I think including them in an external XML file makes it easier to make updates so I've taken that route. My XML looks like this:

<markers>
   <marker lat="" lng="" name=" " phone=”" address="" city="" state="" zip="" url="" />
</markers>

Each marker on the map is represented by a node in the XML doc with attributes that will be used for the display of the map. Note that Google Maps uses latitudes and longitudes to plot markers. While there is a built in function to convert address into lat/long values (a process called geocoding), it wouldn't be efficient to call it for these static locations so I've included the geocoded values into the XML. To batch geocode a bunch of address values I recommend http://www.batchgeocode.com/

Step 3 - HTML Setup
In order for your map to show up within your site you'll need a simple div tag which will house the information from Google.

<div id="googlemap" style="width: 500px; height: 325px"></div>

You can give it whatever ID you like and adjust the width and height accordingly.

Next you'll need to initialize the map by adding some javascript to the HTML body tag like so...

<body onload="load()" onunload="GUnload()">

Step 4 - Javascript
This is where the actual magic happens. All of the settings for drawing the map and plotting the markers are handled via javascript. The following code will show you how to draw a basic map and plot the markers we defined earlier in our XML document.

<script type="text/javascript">
//<![CDATA[
var map = null;

function load() {
   if (GBrowserIsCompatible()) {

      var i = 0;

      // Create the map
      // Make sure this element has the same ID as your div
      map = new GMap2(document.getElementById("googlemap"));
      // Add controls for moving and zooming the map. Use GSmallMapControl for small maps
      map.addControl(new GLargeMapControl());
      // Add controls for switching between regular and satellite views
      map.addControl(new GMapTypeControl());
      // Set the starting position and zoom level when the map loads
      map.setCenter(new GLatLng(38.895222, -77.036758), 13);

      // Read the data from XML
      var request = GXmlHttp.create();
      // Open the XML file
      request.open("GET", "map-markers.xml", true);
      request.onreadystatechange = function() {
         if (request.readyState == 4) {
            var xmlDoc = request.responseXML;
            // Obtain the array of markers and loop through it
            var markers = xmlDoc.documentElement.getElementsByTagName("marker");

            for (var i = 0; i < markers.length; i++) {
               // Obtain the attribues of each marker
               var lat = parseFloat(markers[i].getAttribute("lat"));
               var lng = parseFloat(markers[i].getAttribute("lng"));
               var point = new GLatLng(lat,lng);
               var name = markers[i].getAttribute("name");
               var phone = markers[i].getAttribute("phone");
               var address = markers[i].getAttribute("address");
               var city = markers[i].getAttribute("city");
               var state = markers[i].getAttribute("state");
               var zip = markers[i].getAttribute("zip");
               var url = markers[i].getAttribute("url");
               // Call the function to create the marker
               var marker = createMarker(point,name,phone,address,city,state,zip,url);
               map.addOverlay(marker);
            }
         }
      }
      request.send(null);

      // Function to create the marker and set up the event window
      function createMarker(point,name,phone,address,city,state,zip,url) {
         // Create the HTML text based on the values passed in from XML
         var markerhtml = "";
         if (name != "") markerhtml += "<b>" + name + "</b><br>";
         markerhtml += address + "<br>" + city + ", " + state + " " + zip + "<br>";
         if (phone != "") markerhtml += "Phone: " + phone + "<br>";
         if (url != "") markerhtml += "<a href=\"" + url + "\">" + url + "</a>";

         // Create the map marker
         var marker = new GMarker(point);
         // Add a click event to each marker which will open the HTML window
         GEvent.addListener(marker, "click", function() {
            marker.openInfoWindowHtml(markerhtml);
         });
         i++;
         return marker;
      }
   }
   // Javascript alert for older browsers where Google Maps isn't supported
   else {
      alert("Sorry, the Google Maps API is not compatible with this browser");
   }
}
//]]>
</script>

That's basically all there is to it...

Google Maps Demo of this code in action

Download the source files

Further reading

Much of what I know was learned with a lot of help from these two sites.

The Google Maps API is incredibly complex and you can do much more more than what I've outlined here. Hopefully this post will serve as a baseline and help you get started building your own mashups.

Random Bizarre Firefox / CSS / Flash Bug

I just spent the last several days troubleshooting this bug and since I couldn't find any information anywhere on the web for this obscure problem, I'm posting it here.

For a new site I'm building I have randomly loading promo buttons which are created in Flash. Since they're random and will appear on multiple pages, they need to be transparent. Nothing out of the ordinary, but when I put the page together I noticed a very peculiar error...

ONLY in Firefox 1.5 on a PC (2.0 was fine, Mac was fine) and ONLY when the swf had it's wmode property set to transparent, the swf would load but then be inoperable. No rollover animation or button click events would fire. It just sat there doing nothing on the page.

I tried everything to make it work... multiple embed methods, different flash publishing settings, etc. Nothing seemed to help until a colleague steered me, oddly enough, toward the CSS for my page.

My Flash promos where in a floated div tag for the left column of my page. The container element for the page columns contained a few styles, one of which was "overflow: auto;". This was being used to help clear the floats. A simple switch to "overflow: hidden;" magically solved the problem.

I’m still not 100% as to why this problem occurred. I was careful with my widths and paddings to make sure there weren’t any actual overflow problems but for some reason older versions of Firefox were just not happy with it. So there it is… if anyone else ever encounters this very odd random bug, check the CSS overflow property for the solution.