http://www.developer.com/

Back to article

Integrating Google Maps into Your Web Applications


August 18, 2005

Sci-fi author Duncan Munro's 1950 short story "U-Turn" includes a well-known passage that reads, "May you live in interesting times." I haven't actually read the story, therefore can't say whether it was meant as a blessing or a curse. Regardless, it seems particularly applicable to those of us steeped in Web development, as the last ten years have truly proved to be a whirlwind of excitement. And as the Web platform continues to mature, we're seeing an increasing number of amazing technologies that will take our applications to new levels of power and usability. The most recent development to catch the eye of developers worldwide is the so-called Ajax model, shorthand for Asynchronous JavaScript + XML. This notion seems to have revitalized the Web development community's goal of creating applications that are as rich and responsive as any desktop-based application, but with the added advantage of accessibility via the ubiquitous web browser.

Perhaps the most famous applications embracing the Ajax model is Google Maps. Surely you've played around with this website, perhaps entering your or other addresses of interest, and marveled as how the site responded to zooming and dragging around on the map in seeming real-time. Wouldn't it be great to incorporate Google's mapping capabilities into your applications, taking advantage of not only its enormous database, but also the eminently cool interface that comes with it?

You might be surprised to know Google offers a free Application Programming Interface (API) that makes doing so pretty trivial. Provided you abide by the Terms of Use, and don't surpass 50,000 page views per day without obtaining prior permission, you're free to use this API to embed Google's mapping technology into your website. In this article you'll learn how to do exactly this. Specifically, you'll learn how to integrate maps into web pages, extend the mapping feature to mark locations of interest to your site users, and even display location-specific descriptors simply by clicking on the corresponding icon. But first, for inspiration take a moment to peruse some of the amazing implementations already popping up across the Web:

  • Chicago Crime: A spatially-enabled database of reported Chicago crime.
  • HousingMaps: HousingMaps.com takes advantage of Craiglist and Google Maps to visually depict houses and apartments for sale and rent across the United States.
  • Recent Earthquakes: Charts earthquakes taking place across the globe over the past seven days.
  • Google Maps Mania: An interesting blog covering Google mapping news and projects.

Prerequisites

No special development tools are required in order to take advantage of Google's mapping API; all that is necessary is a text editor, Web browser, and a public Web server from which the scripts can be served. Note the server must be public, you can't develop on an internal server, as each request must communicate with the Google mapping server in order to work correctly. You will however need an API key provided by Google so that usage quotas can be monitored. Begin by reading through some of the usage rules and applying for the key here:
http://www.google.com/apis/maps/signup.html

You'll need to confirm registration by clicking on link provided by you via email, at which time the API key will be provided to you. Paste this key into a text file, as you'll need to integrate it into the scripts used to create the maps.

Your First Map

Incorporating a Google map into your website is surprisingly easy, accomplished with just a few lines of code. Begin by copying and pasting the following snippet into an HTML file, remembering to replace ADD_YOUR_KEY_HERE with your own API key. Then save and upload the file to a Web server.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 

      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

  <head>

    <script src="http://maps.google.com/maps?file=api&v=1

            &key=ADD_YOUR_KEY_HERE" type="text/javascript">

    </script>

  </head>

  <body>

    <div id="map" style="width: 400px; height: 300px"></div>

    <script type="text/javascript">

    //<![CDATA[

    

    var map = new GMap(document.getElementById("map"));

    map.centerAndZoom(new GPoint(-83.022206, 39.998264), 3);

    

    //]]>

    </script>

  </body>

</html>

Executing this script from a Web server produces the following map of my alma mater, The Ohio State University:

The Ohio State University

There are four key components to this script. The following snippet makes the Google map JavaScript script available for use in your script. Note you'll need to supply the API key discussed in earlier in the article.
<script src="http://maps.google.com/maps?file=api&v=1

&key=ADD_YOUR_KEY_HERE" type="text/javascript">

The next snippet specifies the placeholder for the map, and specifies its dimensions. Note you're able to place this line anywhere on the page, positioning it using tables or CSS as desired:

<div id="map" style="width: 400px; height: 300px"></div>

    <script type="text/javascript">

The next snippet creates a GMap object (instantiated from a class found in Google's JavaScript script), readying it for manipulation and display other methods found in the script:

var map = new GMap(document.getElementById("map"));

Finally, the map is centered and displayed on a location declared by latitude -83.022206 and longitude 39.998264. The second parameter of the GPoint constructor determines the height, with 1 offering the lowest (most detailed) height and 16 offering the highest (least detailed).

map.centerAndZoom(new GPoint(-83.022206, 39.998264), 3);

You might be curious to know how I determined the university's latitude and longitude coordinates. At present, Google doesn't offer a means for converting mailing addresses to zip codes, therefore you'll have to depend on some other service for doing so. Thankfully there are several such services out there, perhaps the most compelling of which is geocoder.us. If you're interested in looking up the coordinates for an occasional address, you can do so via the geocoder.us website in seconds. If you're building a commercial application requiring repeated lookups and would like to leave this process to another party, geocoder.us offers a Web Service at a very competitive price. Or if you'd like to take matters into your own hands and manage the conversion process yourself, geocoder.us actually points you in the right direction by offering information about the Perl module Geo::Coder::US and the freely available U.S. Census Bureau TIGER/Line data.

Controlling Mapping Behavior

If you spent a few moments investigating the example map, you noticed that it was draggable by default. That is, holding down the mouse button and moving the cursor will cause the map to reposition accordingly. This feature can be disabled with the following line:

map.disableDragging();
Those of you familiar with Google's service might have wondered why the scaling and repositioning toolbar was unavailable. This feature is disabled by default, but it and all of its corresponding functionality can easily be added with the following command:
map.addControl(new GLargeMapControl());

Adding this to the script produces the following map:

Google Map with Control

There are other types of controls available. I'll enumerate all available controls here:

  • GMapTypeControl: Toggler for switching between the Google map and satellite views.
  • GLargeMapControl: Control such as that seen in the above screenshot.
  • GSmallMapControl: A smaller version of GlargeMapControl, eliminating the zooming scalebar but including the zoom controls.
  • GSmallZoomControl: This control only includes the zooming buttons, eliminating everything else found in the GLargeMapControl.

Adding Mapping Markers

By themselves, the maps are really useful. However, their utility can be taken to the next level by overlaying markers indicating a specific location or set of locations on the map. Sounds daunting right? Surprisingly, it's as easy as the tasks we've carried out thus far: just find the longitude and latitude of the location you'd like to mark, instantiate a new GPoint() object with these coordinates, create a GMarker object based on this point, and finally add that marker to the map. For example, the following point will add a market denoting the location of The Ohio State University's Department of Computer Science and Engineering:


var point = new GPoint(-83.015522, 40.002068);
var marker = new GMarker(point);
map.addOverlay(marker);

Note you'll need to add these lines after executing the centerAndZoom method, or a malformed map will appear. The outcome looks like this:

The Ohio State University's Department of Computer Science and Engineering

It's possible to add numerous markers simply by repeating these lines with different coordinates. For example, suppose a student wanted to visually depict the locations of his classes. The following example shows the locations of three Ohio State campus buildings, including Dreese Labs, Gerlach Hall, and University Hall:


// Fisher Hall
var point = new GPoint(-83.014734, 40.005403);
var marker = new GMarker(point);
map.addOverlay(marker);
// Dreese Labs
var point = new GPoint(-83.015522, 40.002068);
var marker = new GMarker(point);
map.addOverlay(marker);
// University Hall
var point = new GPoint(-83.013307, 40.000610);
var marker = new GMarker(point);
map.addOverlay(marker);
Adding these lines to the script produces the following map:

A Student's Class Map

Adding the pan/zoom control back to the map and zooming in produces a much more detailed representation:

Zooming in on the student's class locations

Adding Location Descriptors

The Ohio State University campus is one of the largest in the world, and it's common to find even seniors asking for directions. Therefore, to be sure the mapping icons will help any student more quickly find their way around. However what if the student is a freshman, and is unable even to match the location to a specific building? What we need is a way to denote both building location and other informational clues such as the building name and street address. This is accomplished using information windows, which can be displayed when the user clicks on the corresponding icon. A screenshot of such a window is shown below, with the corresponding commented code snippet used to create it following:

Including some informational context

This code is admittedly a tad more difficult than what you've seen thus far, but certainly nothing too complex. Because I've created informational windows for each icon (although only one is shown in the above screenshot), I cut down some tedious redundant coding by creating a JavaScript function titled createInfoMarker() which accepts two parameters, a GMarker object and an HTML string containing the location address. Information regarding each of the three building locations follows, with the createInfoMarker() function invoked each time to create the marker and corresponding window:


// Create the marker and corresponding information window
function createInfoMarker(point, address) {
   var marker = new GMarker(point);
   GEvent.addListener(marker, "click",
      function() {
         marker.openInfoWindowHtml(address);
      }
   );
  return marker;
}
// Gerlach Hall
var point = new GPoint(-83.014734, 40.005403);
address = "Gerlach Hall<br />2108 Neil Avenue
    <br />Columbus, Ohio 43210";
var marker = createInfoMarker(point, address);
map.addOverlay(marker);
// Dreese Labs
var point = new GPoint(-83.015522, 40.002068);
address = "Dreese Labs<br />230 North Oval Mall
    <br />Columbus, Ohio 43210";
var marker = createInfoMarker(point, address);
map.addOverlay(marker);
// University Hall
var point = new GPoint(-83.013307, 40.000610);
address = "University Hall<br />230 North Oval Mall
    <br />Columbus, Ohio 43210";
var marker = createInfoMarker(point, address);
map.addOverlay(marker);

Conclusion

This introductory article provided but a taste of what the Google Maps API is capable of. I encourage you to take some time to carefully review the API documentation available on the Google website. Also, take some time to search the Web for enthusiast websites and blogs dedicated to this wonderful service.

About the Author

W. Jason Gilmore (http://www.wjgilmore.com/) is the open source editor for Apress. He's the author of the best-selling "Beginning PHP 5 and MySQL: Novice to Professional" (Apress, 2004. 758pp.). Along with Robert Treat, Jason is the co-author of the forthcoming "Beginning PHP 5 and PostgreSQL 8: From Novice to Professional", due out at the conclusion of 2005. Jason loves receiving e-mail; so don't hesitate to write him at wjATwjgilmore.com.

Sitemap | Contact Us

Thanks for your registration, follow us on our social networks to keep up-to-date