LJ Archive

At the Forge

Google Maps

Reuven M. Lerner

Issue #146, June 2006

Google maps out excellent Web services for keen developers.

During the past few months, we have looked at a number of Web services. Web services is a catch-all phrase for the ways in which Internet companies are making their data available to the general public, for use in people's own applications. Thus, Amazon makes its product catalog available for us to create on-line stores and pricing programs, eBay allows us to search through (and bid on) products available for sale, and Google makes its search results available for viewing and manipulation. Each company restricts the ways in which we are allowed to use the provided data, but the trend appears to be toward additional openness and availability.

Sometimes, that openness comes in a package that is slightly different from the standard form of Web services. That is, some companies make their data available using specialized libraries that call the services for you, hiding the specifics of the calls from your application. One of the most famous examples, and the one that we look at this month, is Google Maps. I have found Google Maps to be one of the most compelling and powerful Web applications out there. Not coincidentally, Google Maps was one of the first applications to make use of Ajax, a term that describes how we can use a combination of JavaScript and XML to grab data from remote servers and then use the results to update a Web page dynamically.

This month, I explain how easy it is to create maps using the Google Maps API. We create some basic maps and even put up small markers indicating locations of interest to us. This will serve as a building block to creating our own mashups, the increasingly popular term for the use of Google Maps to display information culled from a separate database.

Basics

Google Maps, like most Web applications, divides the work between the client (a Web browser) and a server. However, the traditional division of labor has been fairly unequal, putting almost all of the computational onus on the server, giving the browser responsibility for display alone. Ajax changes this, using one or more JavaScript libraries that know how to manipulate the data being displayed in new and interesting ways.

Although Google may someday release an API that will allow us to create our own Ajax applications with its map information, the current release requires that we install and use everything in a single package. That is, Google provides a JavaScript library—or more precisely, a link to a JavaScript library located on Google's servers—that we incorporate into our pages and then use to create a map.

In order to display maps, we need to use that JavaScript library. However, both to keep track of who is using the API and also to ensure that it is being used according to the rules, the library is available only to holders of a key.

Now, we have seen this sort of restriction before, both in Amazon's Web services and also Google's main Web services (that is, for search results). However, the key used in Google Maps is somewhat different; it is keyed both to a particular person (with a Google account) and to a particular URL. This means a map key that works at http://www.example.com will not also work at http://www.example.net.

The first step in using the Google Maps API is to decide under which URL you want to put the maps. I decided to create a new Apache virtual host on my system, which I named maps.lerner.co.il. I then registered with the Google Maps API page (www.google.com/apis/maps), indicating that my applications would be under the URL maps.lerner.co.il. Several seconds later, I was greeted with a page containing my API key, as well as a simple starter page that can display a map. The key is a very long string of ASCII characters, separated by spaces.

Because we will base our applications on HTML, we should take a close look at it:

<!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=
↪ABQIAAAAQQK9JhAXQ9eq-G55qgu1ExScF-BH9Y-SIKcAjU8YFS_
↪uTREdFBSs2-11UWY0kXbUv6argoPyrx3YTg"
type="text/javascript"></script>
  </head>
  <body>
    <div id="map" style="width: 500px; height: 400px"><;/div>
    <script type="text/javascript">

    var map = new GMap(document.getElementById("map"));
    map.addControl(new GSmallMapControl());
    map.centerAndZoom(new GPoint(-122.1419, 37.4419), 4);

    </script>
  </body>
</html>

The HTML document begins by declaring its DOCTYPE, which turns out to be strict XHTML. XHTML is a wonderful idea and ensures that HTML is structured according to all of the strict XML rules. That said, many HTML pages do not adhere to this standard and thus are considered either transitional (meaning, XHTML with a liberal eye) or nothing at all. Because Google Maps tries to be compatible with as many browsers as possible, it benefits greatly from strict adherence to XHTML.

In the <head> tag, we see that there is a <script> tag, which loads JavaScript source from Google's servers at maps.google.com. This ensures that the latest version of the JavaScript library is always available to us and our users. Google promises that when it upgrades the map API, it will give a one-month grace period to allow developers to learn about incompatible changes they might have made.

In the body of the HTML document, we then have a div tag, whose ID is map. This is the node that we will be passing to Google's JavaScript library. The style attribute passed to the div tag contains a width and a height; these determine the size of the map. Your site can display any combination of width and height for the map, allowing you to make adjustments for your particular site design.

Inside of the div, we finally get to the heart of the matter, with three calls.

First, we create an instance of a GMap object. As you might imagine, a GMap represents a particular map within the world of Google Maps. We attach the GMap object to the node with the ID of map. (If the element does not exist, the map will not appear on the screen.) This means, by the way, that you can have more than one map on a particular Web page—simply create multiple <div> tags, each with its own unique ID attribute, and attach different instances of GMap to each <div>.

Once we have created an instance of GMap, we can send it messages to control its behavior. For example, we can add a control to it, allowing us to zoom in and out. In this document, for example, we add a small map control by invoking the addControl() method, passing it a new instance of GSmallMapControl. The GSmallMapControl contains +/– buttons for zooming, as well as arrow buttons for moving the map without having to drag the mouse.

Google provides two other control types as well, known as GSmallZoomControl (which has only the +/– zoom buttons) and GLargeMapControl (which includes everything that the GSmallMapControl does, plus buttons that allow you to jump to a particular zoom level). The controls always appear in the top-left corner of the map, and there is no way to stop you from instantiating more than one of these controls. This means if you aren't careful, you might create more than one control, leading to an ugly map and site.

After creating our map and adding a control to it, we then instruct the map to show us a particular point. Points in a Google map are represented with the GPoint data structure, which represents a single point of longitude and latitude. Longitude and latitude can be represented with either degrees or floating-point numbers; for obvious reasons, GPoints are constructed using the latter. The example document has the following call:

map.centerAndZoom(new GPoint(-122.1419, 37.4419), 4);

The above line of JavaScript sends a centerAndZoom message to the map object. It instructs the map to center itself around the point described by the GPoint and to display the map at level 4. The closest zoom level is 1, and the farthest away is 15, with levels 16–18 showing different types of wrapping. Level 4 allows you to see streets and is a good starting point for people using a map.

It is important to realize that GPoint objects are created with longitude and latitude as their parameters, and not the reverse. This is probably because Google engineers thought in terms of x and y coordinates, which are more natural for math and science people. However, coordinates are often given in latitude, longitude pairs, as opposed to the reverse—so be careful before blindly entering coordinates into a program without checking their order and meaning.

The GPoint created in this default document is in Palo Alto, California, presumably pointing to Google's offices. To look at another area on the map, simply substitute a different set of coordinates. For example, to look at Skokie, Illinois (where I'm currently living), I simply substitute a different set of coordinates:

map.centerAndZoom(new GPoint(-87.740070, 42.037030), 4);

Sure enough, when I reload my page, I'm now looking at a map of Skokie, rather than Palo Alto.

Finally, Google provides us with the ability to switch between three different views, known as map, satellite and hybrid. By default, these controls are shown in the top-right corner and appear thanks to the line:

    map.addControl(new
GMapTypeControl());

As you can probably guess, the above line sends an addControl message to our map object, handing it a new instance of GMapTypeControl.

Markers

Finally, let's look at how we can create a marker, as it is known, on our map. A marker lets us identify a particular point on a map, showing it with one of the Google Maps icons that users recognize. Moreover, although we see this functionality today, we easily can create JavaScript handlers for our markers—such that clicking on a marker causes a JavaScript function to be executed and presumably change the look of our map somehow.

To create a marker, we create a new instance of GMarker, passing it a GPoint:

var myMarker = new GMarker(new GPoint(-87.740000, 42.030000));

Now that we have created our marker, we can display it on the map:

map.addOverlay(myMarker);

If you add the above two lines within the <script> section of the HTML file, you immediately will see a red marker appear on the screen.

Now, here's where some real magic begins. Everything that we have done so far is done in JavaScript and HTML. Both of these are read and handled by the browser, but they are created by the server. This means that if we create our HTML file not as a static file, but rather dynamically (that is, from a server-side program), we can do all sorts of neat things with the JavaScript.

For example, we can create multiple GMarkers, simply by assigning them to different variables and then attaching each of them to the map. If our Google Maps page is being run by PHP, we can write a short PHP program that inserts appropriate JavaScript code into the page. For example:


<?php
$a = array(-87.740070, -87.730000);
 $count = 0;

foreach ($a as $v) {
    echo "var myMarker$count = new GMarker(new GPoint($v,
42.037030));\n";
    echo "map.addOverlay(myMarker$count);\n";
    $count++;
  }
?>

If we put the above inside of the <script> section of our page, and if we then rename the page to index.php (instead of index.html), we quickly will see two markers on the page, with slightly different longitudes and the same latitude.

Notice how the above code uses PHP's echo command to insert text into the HTML document when it executes. Also notice that we need to add semicolons—one to end the line of JavaScript (inside of the quotes) and one to end the line of PHP (outside of the quotes). These sorts of issues are always a headache when writing a program that writes another program. Finally, notice how we had to create arbitrary new variable names to avoid using the same variable over and over, and thus losing all but one of the markers. The simplest way to do this is with a $count variable, which then assures that you will have a unique variable name for each marker.

Conclusion

Google Maps is a wonderful Web application. But for developers, it's also a platform on which we can create all sorts of new applications and services that depend on maps. In particular, by dynamically creating an HTML document from a programming language, we can insert data that JavaScript can then incorporate into a map. Next month, we will see how we can do this, creating our own mashup—grabbing information from one data source and then displaying it on a Google map.

Resources for this article: /article/8939.

Reuven M. Lerner, a longtime Web/database consultant, is currently a PhD student in Learning Sciences at Northwestern University in Evanston, Illinois. He and his wife recently celebrated the birth of their son Amotz David.

LJ Archive