Why is this page text-only?

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.

Del.icio.us Digg Yahoo! My Web Seed Newsvine reddit Technorati Facebook StumbleUpon Mark in ma.gnolia Google Bookmarks Windows Live

TrackBacks

TrackBack URL for this entry:
http://www.codescene.com/cgi-bin/mt/mt-t.cgi/63

5 Comments

i am super rivted by this.

I had to remove the & symbols for the XML to work. (This is the first time I've ever worked with XML). Is that usual?

Oh yeah - and this was an awesome help. Thanks for the resource.

Cheers,
Phoenix.

Characters like ampersands, quotes, and greater/less than signs are illegal inside XML nodes unless they're properly encoded or encapsulated within a CDATA element.

See http://www.w3schools.com/xml/xml_cdata.asp for more info

You don't happen to know how to make the map come up in Satellite view by default, do you?

map = new GMap2(document.getElementById("googlemap"));
map.setMapType(G_SATELLITE_MAP);

See Google Maps Documentation for more.

Leave a comment