Buy this Book
Print Book $29.99 Read it Now!
Print Book £20.99
Add to UK Cart
Reprint Licensing

Google Maps Hacks
Google Maps Hacks

By Rich Gibson, Schuyler Erle
Price: $29.99 USD
£20.99 GBP

Cover | Table of Contents


Table of Contents

Chapter 1: You Are Here: Introducing Google Maps
In February of 2005, Google quietly announced the debut of a new service, Google Maps, that changed the face of mapping and cartography on the Web for an overwhelming number of people. Gone were the tiny, slow-loading, and sometimes ugly digital maps that people were pretty much accustomed to using on the Web, maps that fell below the "fold" of a web page, and were often impossible to navigate. Instead, using the latest in web browser scripting technology, Google Maps offers a fast-loading, tiled map display, a simple yet deep user interface, asynchronous display updates in place of the tiresome click-and-reload routine, and, ultimately, even a rich scripting API. Although many of these features had been seen before in one place or another, no one had seen them all integrated with the attention to detail that we've come to expect from Google. Let's take our first look at how Google Maps changed how people use maps on the Web forever.
Sometimes you need a map to the map.
Google applied its trademark, carefully designed simplicity, to provide us with its (first) view of place. Go to http://maps.google.com/, and you'll get the view shown in Figure 1-1. If you want maps of the United Kingdom, try http://maps.google.co.uk/, and you'll get the view in Figure 1-2. A similar map exists for Japan at http://maps.google.co.jp/.
This shows us what appears as a standard Google search box (called the Location Search box), an overview or orientation map of the country in question, and a results area with instructions and sample searches.
Figure 1-1: http://maps.google.com/
Figure 1-2: http://maps.google.co.uk/
Please remember that this book was written using beta software, and the Google engineers are continually tinkering with the site in order to provide the most compelling possible system. This means that things will change!
Google Maps is a web mapping service that solves the same old problem of online mapping. So why, ten years or more into the web revolution, is Google Maps such a big deal? Some of the excitement comes from the Google name and its philosophy. Google states on its corporate philosophy page at
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Hacks 1–9: Introduction
In February of 2005, Google quietly announced the debut of a new service, Google Maps, that changed the face of mapping and cartography on the Web for an overwhelming number of people. Gone were the tiny, slow-loading, and sometimes ugly digital maps that people were pretty much accustomed to using on the Web, maps that fell below the "fold" of a web page, and were often impossible to navigate. Instead, using the latest in web browser scripting technology, Google Maps offers a fast-loading, tiled map display, a simple yet deep user interface, asynchronous display updates in place of the tiresome click-and-reload routine, and, ultimately, even a rich scripting API. Although many of these features had been seen before in one place or another, no one had seen them all integrated with the attention to detail that we've come to expect from Google. Let's take our first look at how Google Maps changed how people use maps on the Web forever.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Get Around
Sometimes you need a map to the map.
Google applied its trademark, carefully designed simplicity, to provide us with its (first) view of place. Go to http://maps.google.com/, and you'll get the view shown in Figure 1-1. If you want maps of the United Kingdom, try http://maps.google.co.uk/, and you'll get the view in Figure 1-2. A similar map exists for Japan at http://maps.google.co.jp/.
This shows us what appears as a standard Google search box (called the Location Search box), an overview or orientation map of the country in question, and a results area with instructions and sample searches.
Figure 1-1: http://maps.google.com/
Figure 1-2: http://maps.google.co.uk/
Please remember that this book was written using beta software, and the Google engineers are continually tinkering with the site in order to provide the most compelling possible system. This means that things will change!
Google Maps is a web mapping service that solves the same old problem of online mapping. So why, ten years or more into the web revolution, is Google Maps such a big deal? Some of the excitement comes from the Google name and its philosophy. Google states on its corporate philosophy page at http://www.google.com/corporate/tenthings.html that "you can make money without doing evil." However, more of the interest in Google Maps may stem from other ideas stated on the philosophy page—for example, "The interface is clear and simple" and "Pages load instantly."
Clean pages and fast performance? A commitment to avoid doing evil? Which drives traffic and mind share? Maybe at this moment on the Web you can have it all. In addition to these features, Google Maps also offers a number of innovations in web user interfaces.
Single search box
The first thing that draws attention is that Google uses a single search box for location searches. Do you want to look up an address? Just type it in the box. No more tabbing between different fields for street address, city, state, and ZIP Code! (In Internet Explorer, you can even paste multi-line addresses into this box, believe it or not.)
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Find Yourself (and Others) on Google Maps
Google Maps supports many ways to specify location.
Using addresses to find a place makes a lot of sense for places that have an address, but what do you do when you don't have an address? Fortunately for you, the Google Maps team has supplied a number of additional ways to find yourself.
I suspect that the goal is to create a system in which, if you can imagine a somewhat standard way of representing a location, then Google Maps will support it. The functionality is not quite there yet, but it does support a lot of ways of finding places. As with all of the hacks in this book, and as a general philosophy of life, experimentation is your friend!
The number one rule for finding places using Google Maps is that if there is a way of specifying location that makes sense to you, go ahead and try it! As we saw in "Get Around http://maps.google.com" [Hack #1] , standard addresses work, but so does entering a city and state, or a ZIP Code alone. Street intersections also work, as long as you add a city and state.
You can also enter coordinates as latitude and longitude, like 38, -122, or 38 N, 122 W. Most modern people don't relate to latitude and longitude directly, but it is a compact and precise way to mark a location.
Google Maps is good at searching by business name. You can search by business name, city, and state—for example, "O'Reilly Media, Sebastopol, CA"—with good results. Entering a business name and a city, or a business name and a state, brings up a list of possible matches.
The best Google Maps feature ever is the proximity search, at least for one of my friends, who is a vegetarian and travels a lot. Before Google Maps, he spent a lot of time on other map services planning for trips. A common query was for the closest Whole Foods Market in whatever city he was visiting. Now he can just type his query into the single search box: "whole foods market near Boston, MA." As long as he remembers to change Boston, MA to his current city, he is set. Table 1-1 shows examples of searches that do and don't work.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Navigate the World in Your Web Browser
There is no doubt about it: Google has significantly raised the bar for user interfaces to maps on the Web. Here's why.
When Google Maps was launched in February 2005, the public response was instant and almost overwhelmingly positive. Although the remarkable speed with which any map appeared, tile by tile, had a great deal to do with people's appreciation of Google Maps, most of the praise and recognition was saved for the browser interface itself. The Google Maps user interface is clean, simple, straightforward, quick loading, and easy to use. In other words, it offers yet another classic Google user experience.
The main thing about the Google Maps user interface that really wows everyone the first time they see it is the drag panning. Go to any location in Google Maps, position the mouse pointer anywhere on the map, click and hold your left mouse button, and then move the mouse itself. Lo and behold—the map moves with it, and the page in your browser doesn't even reload! Releasing the mouse button, of course, causes the map to stop panning.
You'll notice that, in the background, your browser has already loaded many of the tiles outside your original view, so that you don't have to wait for them to load as you're panning around—that is, unless you're on a slow Internet connection, or you try to pan very quickly from one edge of the map to the other.
If dragging the map feels a bit wild or difficult to control, the Google Maps interface also allows you to double-click your left mouse button anywhere on the map to recenter it at that location. Double-clicking to recenter gives you a more precise, but somewhat less dynamic way to pan around the map.
The ability to click and drag the map around in the browser window, while not, strictly speaking, new, has never been seen before in a major mapping service on the Web. Gone are the days when browsing a map on the Web involved a tedious wait for the entire web page to reload every time you tried to recenter or zoom the map! Hooray!
Over on the left side of the map, you should see a number of controls in gray and black, as shown in Figure 1-5. If panning by dragging or double-clicking doesn't suit you, you can use the four arrow buttons to scroll the map north, south, east, and west. The somewhat less obviously labeled button in the center of the other four, which depicts four arrows pointing inwards, returns you to the original view of the last thing you searched for. This button lets you pan around the map, zoom in and out to your heart's content, and then click the return button to go right back to the place you were originally looking at.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Get the Bird's-Eye View
Maps are good, but a picture is worth…
Maps show what the mapmaker chooses to show. Google Maps, like most of the online map services, shows maps that are designed primarily for getting around in a car. In America, we pretend we've (d)evolved into homo automobilious, but despite our best efforts there is more to the world than scenery and billboards flying past the bug-smeared windshield.
One neat feature of Google Maps is the ability to flip between viewing a map and viewing satellite imagery. In Figure 1-8 we see a map of the Upper West Side of Manhattan, with an odd little shape sticking into the Hudson River on the left side. By clicking on the Satellite link on the upper-right side of the window, you get satellite and aerial imagery.
Figure 1-8: Upper West Side Manhattan
The aerial view in Figure 1-9 provides a lot more context! You can see the buildings and Riverside Drive. You can even make out individual boats at the 79th Street Boat Basin. You can use the same navigation tricks to pan around in satellite and aerial imagery as you can on the map layer [Hack #3] .
Figure 1-9: Aerial view of the Upper West Side and the 79th Street Boat Basin
The satellite imagery's level of detail varies by where you're looking; some places have much more detail than others.
You can use the aerial imagery as a sanity check. For example, let's say you are in the North Bay area and are interested in dairy products. You could search for cheese near Petaluma, CA and get a map like Figure 1-10.
Figure 1-10: Looking for cheese in all the wrong places
To visit Rouge et Noir Cheese Factory (http://www.marinfrenchcheese.com/), you could click on the link on the right side in the list of results, zoom in a bit, and flip to satellite view to get the view in Figure 1-11.
Where's the cheese? It doesn't look like it is there. Could it be in that circular compound on the right-hand side? Maybe, except I happen to know that this isn't the case. It seems that there's a disconnect between databases at Google. The business listing for Rouge et Noir puts it at 7500 Red Hill Road, Petaluma, CA 94952, but the map pointer is 4.5 miles northeast. Of course, this
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Driven to a Better User Interface
Driving directions and the single search box.
How much work does it take to get driving directions? With MapQuest, you need to click on a link to the Directions page, enter your starting street address, hit Tab (or even worse, take your hands off the keyboard, put them on the mouse, and click on the next field), enter your city, hit Tab, enter your state, hit Tab, enter your ZIP Code, hit Tab, and then repeat that Enter-Tab ballet for your destination.
In Google Maps, you enter your starting street address, city, state, and (optional) ZIP Code, then to, and then the street address, city, state, and (optional) ZIP Code of your destination—into the single search box. Would you trade a click and seven tabs or clicks for a single to? I sure would! In addition, Google Maps provides lots of alternatives for asking directions. The usual way is to enter the beginning and ending destinations into the search box [Hack #2] .
To get directions from O'Reilly Media to the San Francisco airport, you can enter the starting address and the airport code:
1005 Gravenstein Hwy N, Sebastopol, CA 95472 to SFO
You can even get directions from one airport to another. For example, for directions from San Francisco International to Oakland International try SFO to OAK. This pulls up the driving directions shown in Figure 1-14.
Figure 1-14: Driving directions from the San Francisco to the Oakland airports
When I get driving directions, I'm usually familiar with either the starting or ending location, but not both. Google provides a neat map-within-a-map effect to help navigate that last little bit. If you click on the Start Address or End Address links in the top of the results area on the right of the screen, a mini-map appears in the info window of the starting or ending address (Figure 1-15).
Figure 1-15: A detailed map of the destination
You can also click on the individual steps in the driving directions to get a mini-map for that navigational maneuver. The mini-map that appears is a complete map, with its own zoom (but not pan) controls, so you can position the map, zoom in, and print the map and directions. To add another level of cool, flip the mini-map to satellite view, as shown in Figure 1-16.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Share Google Maps
Found something good? Email a link, bookmark it, or post it on your web site.
Are you having a party and needing to let people know where it will be held? Did you find a cool spot that you want to show your friends? Google Maps can create an email with a link that will show your friends (mostly) the same view you see—or generate a link to post on your own web site.
Without maps, many of us are reduced to near-incomprehensible grunts if forced to provide directions to our homes. Even if we've lived in the same place for years, our direction-giving process too often includes putting a hand over the phone handset and asking whoever is around, "What is the name of that street?"
The problem doesn't end there. Even if we are good at providing directions, our would-be visitor must keep track of fragments of data such as "the red mailbox" and "right after the hill—and if you hit the corner, you've gone too far." With online map services, though, most of the time it is enough just to have a street address, and with most, emailing or posting a link to a map helps a visitor find the location quickly.
Figure 1-20 shows driving directions from W 88th St and Broadway, NY, NY to W 92nd St and Central Park West, NY, NY. It also includes a destination mini-map.
Figure 1-20: Getting around New York in Google Maps
Click the Email link just under the line that includes the Map and Satellite links, and Google opens your email client and inserts this link to this map, along with a set of driving directions, in the body of the email:


	http://maps.google.com/maps?q=W+88th+St+and+Broadway,+ny,+ny+

	  to+W+92nd+St+and+Central+Park+West,+ny,+ny&ll=40.789110,-73.966550&spn
	  =0.007782,0.013467&hl=en
All you need to do is fill in the email address of your friend and send it off.
Google Maps makes deep use of JavaScript to dynamically redraw the map without (apparent) requests to the server. This means that the location bar in your browser does not get updated. This only becomes an issue when you decide to bookmark a map to use later.
When you bookmark Google Maps, you find that you've bookmarked the overview map of the whole United States—almost certainly not what you intended! Fortunately Google has provided a way out. Next to the Email link, under the Map and Satellite links, is a link to "Link to this page," as shown in Figure 1-21.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Inside Google Maps URLs
Gain control of your links to Google Maps by understanding the URLs.
"Share Google Maps" [Hack #6] showed how to have Google Maps generate a link (i.e., Uniform Resource Locator or URL) that creates a view of the current map. A little exploration of Google Maps URLs can provide a lot of power!
We have no particular inside information, so much of what follows—especially what I think the abbreviated names stand for—is just semi-knowledgeable guesses. Let's start with a basic URL. This is what you get if you search for Key West, Fl and then click on "Link to this page."
http://maps.google.com/maps?q=Key+West,+Fl&hl=en
The http://maps.google.com part should be familiar. This is the basic Google Maps address. Next, /maps is a program running on Google's servers that generates maps. Web programs can accept parameters. The syntax for parameters is to start with a question mark and then put the name of a parameter, an equal sign, and the value of the parameter. If you need a second (or third, or more) parameter, you put an ampersand between the first value and the second parameter's name. So ?q=Key+West,+Fl&hl=en means there is a parameter named q with the value Key+West,+Fl and a parameter named hl with the value en.
Note that the spaces in "Key West, Fl" have been replaced with plus signs. This is because spaces aren't allowed in URLs and must be escaped.
The parameter hl is the language for the results, and q is the query, or location that you are searching for. If you speak French, replace the en with fr, and so on. If you leave off the hl parameter, Google Maps will try to display things in whatever language the user's web browser prefers.
The q or query parameter can be any of the things that are discussed in "Find Yourself (and Others) on Google Maps" [Hack #2] . For example, here is the URL to a map for latitude 38 degrees north, longitude 122 degrees west:
http://maps.google.com/maps?q=38,-122&hl=en?
Google Maps follows the convention observed by most web mapping software and Geographic Information Systems, and uses negative values to denote latitude south of the Equator and longitude west of the Prime Meridian.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Generate Links to Google Maps in a Spreadsheet
Get a handle on your own data with Google Maps.
What if you could create a private (or public) web page with links to Google Maps for each of the people in your company? Or all the members of your social club or church? You would be able to click on the names of people in your group and pop up a map of their location. Well, you can!
In "Inside Google Maps URLs" [Hack #7] , we examined the structure of Google Maps URLs. Now we will use that information to create links to Google Maps that show your own contacts. We'll assume that you've got your contacts in a spreadsheet program, such as Microsoft Excel, Gnumeric, or OpenOffice Calc.
Figure 1-22 shows a sample data set with a name, street address, city, state, and ZIP Code set up in columns. This spreadsheet is available as http://mappinghacks.com/google/sample_data.xls.
Figure 1-22: Name, address, city, state, and ZIP Code in spreadsheet columns
We can go from this format to a full HTML link in Excel. The HTML link for each element will look like this:
	<li><a href="http://maps.google.com/maps?q=1005+Gravenstein+Hwy
	          +N.,Sebastopol,CA,95472+(O'Reilly)&hl=en">
	O'Reilly & Associates</a></li>
The li tag will put each line in an HTML bulleted list. You will be able to click on the name and pop up a map centered on the address that goes with that person or company.
The first step is to use the concatenation function to put the name, address, city, state, and ZIP Code together in a new column. You can do this by using either the concatenation function or the shortcut & that does the same thing:
	=CONCATENATE(B4,",",C4,",",D4,",",E4,"(",A4,")")
or:

	=B4 & "," & C4 & "," & D4 & "," & E4 & "(" & A4 & ")"
This creates an address that looks like this:
1005 Gravenstein Hwy N.,Sebastopol,CA,95472 (O'Reilly)
You'll note that we use the custom location title trick [Hack #7] to associate the locations on the map with the names from our spreadsheet.
Next, we'll replace the spaces with plus signs and ampersands with
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Use del.icio.us to Keep Up with Google Maps
Other people want to help you keep up with Google Maps (and anything else)!
What would you say to a world-wide community of people who spend a great deal of effort to maintain a chaotic but powerful set of links to most of the most interesting material that is available on the Web? How about "thank you" and welcome to http://del.icio.us/?
Quoting from http://del.icio.us/doc/about, Joshua Schacter created del.icio.us as a:
…social bookmarks manager. It allows you to easily add sites you like to your personal collection of links, to categorize those sites with keywords, and to share your collection not only between your own browsers and machines, but also with others.
One key to the service is that your collection of links is intrinsically shared with others. So you can use del.icio.us to manage your own bookmarks, or you can just browse other people's links. Once you create an account by going to http://del.icio.us/register and picking a username and password, you can use the service to bookmark your own links.
A major part of the power of del.icio.us comes from the ability to tag your links. A tag is just a bit of text that you feel categorizes the link. Figure 1-24 shows a page of links that I tagged with the gmaps tag.
Figure 1-24: del.icio.us posts about Google Maps
Since all bookmarks on del.ico.us are shared, you can look at other sites that people have tagged with the same tags. So if you wanted to see all of the sites tagged with gmaps, you can click on "gmaps from all users" or go directly to this url: http://del.icio.us/tag/gmaps. Or to see the sites tagged with gmap, try http://del.icio.us/tag/gmap. Other people use googlemaps and google_maps, so you can get to those with http://del.icio.us/tag/googlemaps and http://del.icio.us/tag/google_maps.
Once you've looked at other people's links, you will want to create your own. Joshua provided some nifty little bookmarklets that you can drag onto your bookmark toolbar. When you find a page you want to remember, you just click on this bookmarklet in your own toolbar. This will bring up a form like that shown in Figure 1-25. (There are a few different bookmarklets, so yours might look slightly different.)
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Introducing the Google Maps API
The Google Maps site at http://maps.google.com is awesome, with an easy user interface, one-box searching, and integrated satellite imagery. But it gets better! The Google Maps team has made it possible to include Google Maps with almost all of its great features onto your own web pages. They have done this by providing an open Application Program Interface, or API.
An API defines a standard way for one program to call code that lives within another application or library. The Google API defines a set of JavaScript objects and methods that you use to put maps on your own web pages.
Before Google Maps, it was much harder to put simple maps on your own pages. MapQuest had a program that let you create a link to a map. You could not embed the map on your own page, you could not put it into a frame, you couldn't even use Target=_new to open a new browser window.
There were—and are—open source solutions to generate maps. For example, the UMN Mapserver (http://mapserver.gis.umn.edu) is very powerful, allowing you to do things that Google Maps cannot yet equal, but there is a rather steep learning cliff. There are also industry standards for web mapping promulgated by the Open Geospatial Consortium (OGC) at http://www.opengeospatial.org.
The OGC-defined Web Mapping Service (WMS) and Web Feature Service (WFS) standards define a powerful web services interface to geospatial data. There are now free and easy-to-use open source clients for WMS and WFS data. For example, you can use the open source JavaScript library from http://openlayers.org/ to access public data sources and put free maps on your page.
These are great options that either were not available or were not easy to use when the Google Maps API was released. Some folks argue that Google did nothing new. There was free data out there, and there were web-enabled GIS systems. But clearly Google did something.
Creating feature-complete interfaces to geographic data that are so complex as to be inpenetrable by all but the highest of high priests seems to be nearly inevitable. Programmers start with a simple model, and then the world, the data, and the weight of history intrude to "complexify" our models and break our metaphors. When Walt Kelly wrote "We have met the enemy and he is us," he could have been describing the creators of most geospatial apps.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Hacks 10–16: Introduction
The Google Maps site at http://maps.google.com is awesome, with an easy user interface, one-box searching, and integrated satellite imagery. But it gets better! The Google Maps team has made it possible to include Google Maps with almost all of its great features onto your own web pages. They have done this by providing an open Application Program Interface, or API.
An API defines a standard way for one program to call code that lives within another application or library. The Google API defines a set of JavaScript objects and methods that you use to put maps on your own web pages.
Before Google Maps, it was much harder to put simple maps on your own pages. MapQuest had a program that let you create a link to a map. You could not embed the map on your own page, you could not put it into a frame, you couldn't even use Target=_new to open a new browser window.
There were—and are—open source solutions to generate maps. For example, the UMN Mapserver (http://mapserver.gis.umn.edu) is very powerful, allowing you to do things that Google Maps cannot yet equal, but there is a rather steep learning cliff. There are also industry standards for web mapping promulgated by the Open Geospatial Consortium (OGC) at http://www.opengeospatial.org.
The OGC-defined Web Mapping Service (WMS) and Web Feature Service (WFS) standards define a powerful web services interface to geospatial data. There are now free and easy-to-use open source clients for WMS and WFS data. For example, you can use the open source JavaScript library from http://openlayers.org/ to access public data sources and put free maps on your page.
These are great options that either were not available or were not easy to use when the Google Maps API was released. Some folks argue that Google did nothing new. There was free data out there, and there were web-enabled GIS systems. But clearly Google did something.
Creating feature-complete interfaces to geographic data that are so complex as to be inpenetrable by all but the highest of high priests seems to be nearly inevitable. Programmers start with a simple model, and then the world, the data, and the weight of history intrude to "complexify" our models and break our metaphors. When Walt Kelly wrote "We have met the enemy and he is us," he could have been describing the creators of most geospatial apps.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Add a Google Map to Your Web Site
Here's how to get started using the Google Maps API.
At O'Reilly's Where 2.0 converence on June 29, 2005, Google announced an official and documented API for Google Maps. The API makes it possible for anyone to add a Google Map to a web page by cutting and pasting a few lines of JavaScript from the Google Maps Developer's site.
People reacted to the new API in one or more ways. My first act was to scratch my own itch by writing a bit of code to display my GPS waypoints on a Google Map. Fortunately, better GPX-to-Google Maps solutions have been created, one of which is documented in "View Your GPS Tracklogs in Google Maps" [Hack #37] . After scratching that itch, I looked to our Geocoder.us site. Schuyler had spent a lot of time figuring out the Census Bureau's public TIGER/Line Map Server API, and how to display the resulting map with a neat little zoomable interface. The results were slow and clunky, but they worked.
The Google Maps API gets rid of the need for that level of head scratching! The march of progress in computers (possibly in society at large) works by first figuring out ways to do new things, and then progressively making those tasks easier, and leaving the old practitioners to eat cat food and write programs for their Osborne luggable computer.
I used Google Maps to bring the geocoder.us site into the protective embrace of the Google Maps API. Geocoder.us, online at http://geocoder.us/, is a free U.S. address geocoder. You can go to the web site and get the latitude and longitude for a U.S. street address. You can also use a web service interface to get the latitude and longitude automatically for a group of addresses [Hack #62] . You can geocode using Google Maps by scraping their search results, but it's not a part of the official API, and doing so violates Google's terms and conditions of service. By contrast, the Geocoder.us site is based on free data without limited terms of service for non-commercial use.
Figure 2-1 shows the results of geocoding the address of O'Reilly Media's headquarters with the original TIGER/Line map, with a pushpin showing the location of the address that we just looked up. We'd like to replace this somewhat slow map generated by the Census Bureau with the much faster, more attractive, and more easily navigable maps offered by Google Maps. (The original Geocoder.us map view can be seen at
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Where Did the User Click?
Find the location of a click on a map and display it on your web page.
Google Maps makes it easy to put an interactive map on your web page. At http://www.naffis.com/maphacks/latandlon.html you can click on a map and have the corresponding latitude and longitude displayed in a Google Maps info box.
In Figure 2-4 you can see the location of the Washington Monument.
Figure 2-4: The Washington Monument at 38.88941 N, 77.03517 W
This site solves the common problem of figuring out the coordinates of a location from a map view and is an example of the sort of quick hack that Google Maps has made possible. This page illustrates one way to get the latitude and longitude from a click on a map and display results in an info box. So how can you do it? At http://mappinghacks.com/projects/gmaps/click.html there is a simplified example of updating a form from the coordinates of a click on a map.
This is the Hello World map with three changes. An HTML form has been added to receive the latitude and longitude from the click event:
	<form>
	Latitude: <input type="text" value="38.4094" id="click_lat"
	onclick="this.blur()">&nbsp;
	Longitude: <input type="text" value="-122.8290" id="click_long"
	onclick="this.blur()">&nbsp;
	</form>
In the script, the latitude and longitude used to set the initial map location with centerAndZoom( ) now comes from these form elements. This code defaults to starting at 38.4094 N, 122.8290 W. Change those values to change the initial focus of the map. The important change to the script is the addition of a GEvent.addListener. This code and the above form can be pasted into the body of your HTML page. Change the developer's key and you can capture clicks on a map:
	<script src=
	     "http://maps.google.com/maps?file=api&v=1&key=replacewithyourkey"
	type="text/javascript">
	</script>

	<div id="map" style="width: 400px; height: 300px"></div>
	<script type="text/javascript">
	//<![CDATA[

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

	       // center and zoom to the lat/long in the form
	       map.centerAndZoom(new GPoint(
	                   document.getElementById('click_long').value,
	                   document.getElementById('click_lat').value), 3);

	       GEvent.addListener(map, 'click',
	           function(overlay, point) {
	               if (point) {
	                   document.getElementById('click_lat').value = point.y;
	                   document.getElementById('click_long').value = point.x;
	               }
	           }
	       );
	       //]]>
	</script>
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
How Far Is That? Go Beyond Driving Directions
Draw routes and calculate distances on your own Google Maps.
How far is it? That's a basic question we often ask of maps. Google Maps' driving directions answer that question, but driving directions are not (yet) accessible to the developer's API. More importantly, they simply give driving distances assuming the optimal route, where optimal is defined as getting there as quickly as possible in an automobile. They are not optimized for "scenic drive" or "safest bicycle route" or "quiet stroll" or "jog around the park."
There are at least two sites that allow you to create routes and calculate distances by clicking on maps. The Gmaps Pedometer at http://www.sueandpaul.com/gmapPedometer/ shown in Figure 2-6 estimates cumulative distance—and even includes a calorie counter.
Use the standard map controls to zoom into your area of interest, and then click Start Recording. When you double-click a point on the map, it will recenter to that spot and add a marker there. The second time you click, the map will recenter to your new point, the marker will be moved, and a line will be drawn from the last point clicked to this one. Each time you do this, the Total Distance and Last Leg Distance fields will be updated.
Figure 2-6: Sue and Paul's Gmaps Pedometer
Handling double clicks is a bit awkward and browser dependent. Sue and Paul are doing browser detection and then setting the appropriate event handler based on the browser:
	if (navigator.appName == 'Microsoft Internet Explorer'){
	        document.ondblclick = handleDblClick;
	        bIsIE = true;

	    } else {
	        window.ondblclick = handleDblClick;
	        bIsIE = false;
	    }
Do you see the difference between the two ondblclick events? It is a difference in how they implement the Document Object Model. Internet Explorer handles double-clicks at the document level, hence document.ondblclick and everyone else (well, everyone else according to this code) uses the window object, so window.ondblclick. In both cases when there is a double-click the variable bDoubleClickHappened
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Create a Route with a Click (or Two)
You can even take Google Maps where the roads don't go.
Driving directions don't always take you where you want to go, or they may take you the wrong way. You can use a little Google Maps hack to build up your own list of points that can be saved in different formats that can be loaded into a GPS or other tool that supports the GPX standard.
The click-to-route tool is at http://mappinghacks.com/projects/gmaps/clicktoroute.html. You click on the map to create a continuous track. An example is shown in Figure 2-9.
Figure 2-9: No roads—only walkers, horses, and bikes here!
Once you've created your route, click on one of the Export buttons. Clicking on CSV (Comma Separated Values) generates a pure-text file with the latitude and longitude separated with commas. GPX Track makes a GPX Tracklog file. GPX Route generates a set of points that can be loaded into a GPS. Here is a sample of the route as a CSV file:
	38.4047068183193, -122.84743666648865
	38.4041771393969, -122.84764051437378
	38.403941725296505, -122.84796237945557
And here is an example of a GPX Tracklog:
	<?xml version="1.0"?>
	<gpx>
	<trk><name>Google Maps Hacks is Good</name>
	<trkseg>
	<trkpt lat="38.41324840580697" lon="-122.84113883972168"></trkpt>
	<trkpt lat="38.402688973080245" lon="-122.82877922058105"></trkpt>
	<trkpt lat="38.4049085997449" lon="-122.84637451171875"></trkpt>
	</trkseg>
	</trk>
	</gpx>
Many GPS units have a limit on the number of points that can be used in a route. This GPSBabel command will simplify your list of points to 30.
	gpsbabel -r -i gpx -f route.gpx \
	    -x simplify,count=30 -o gpx \
	    -F shorter_route.gpx
See "Load Driving Directions into Your GPS" [Hack #35] for more on reducing the number of points and loading a route file into your GPS.
This hack is almost identical to "How Far Is That? Go Beyond Driving Directions" [Hack #12] , with the addition of one function that generates the formatted list of points, and buttons to call this function. The buttons are inserted with this HTML code:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Create Custom Map Markers
Adding custom markers to your Google Map can enhance its readability and appeal.
Almost immediately after the Google Maps API announcement, Jeff Warren made a hack that used custom icons to do a map depicting Star Wars ATATs attacking Google's home town, Palo Alto, as shown in Figure 2-10. You can launch your own Imperial assault on Google's home base at http://www.vestaldesign.com/maps/starwars.html.
This hack immediately demonstrated the flexibility of Google's new API. If you wanted to use a house icon instead of the generic marker, you could. Likewise, if you wanted to make a multiplayer game using Google Maps, the API was flexible enough to allow you to let users submit their own icons.
To create an icon, you need two things: a foreground image for the icon and a shadow image in the PNG 24-bit file format. If you are only changing the color of the generic marker, you can reuse the generic shadow, but for this hack we're going to make something completely different.
Instead of doing something generic and boring, I decided to take a headshot of a friend of mine and turn it into a Google Maps marker icon! I grabbed a suitable shot from a digital photo, loaded it into Adobe Photoshop, and started erasing, as shown in Figure 2-11. About halfway through, I could tell this was going to make a great foreground image.
Figure 2-10: You too can send Imperial ATATs to attack Google's headquarters
If you're not into commercial software, the GNU Image Manipulation Program, or GIMP, offers an open source alternative with the same basic features. You can find the GIMP at http://www.gimp.org/.
Once I finished erasing around Karl's head, I scaled down the image, cropped it, and expanded the canvas to give Karl's head some breathing room. I wouldn't want him to get claustrophobic, and when we start working on the shadow, we're going to need a bit of extra room. You can see the finished result in Figure 2-12.
Finally, I went to the File → Save for Web option, and saved my file in the PNG-24 format with transparency. 24-bit PNG format is ideal for custom map icons, because it's lossless and the alpha layer support allows for some wonderful transparency effects.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Map a Slideshow of Your Travels
Show your friends and family not just what you saw on your vacation, but where you saw it.
Wouldn't it be cool to be able to show your friends and family not only what you saw on your vacation, but also where each photo was taken? Thanks to Google Maps' simple API, you can very easily make a slideshow to put on your web site.
Travelogue slideshows are as old as the film slide projector itself. The Google Maps API and a dab of JavaScript can dust off the ancient tradition, and show off the places you've been with an amazing amount of detail. What's more, little touches like the API's animated map panning function lend a sense of motion to the story of your travels. Figure 2-15 shows a slideshow I put together of my vacation last year to the Burning Man Festival in Black Rock City, Nevada. This slideshow can also be seen online at http://igargoyle.com/slideshow.html.
Figure 2-15: Make a slideshow that will captivate your friends and family
For my map, I took the photos from Black Rock City and added titles and descriptions for each image to better tell the story of my trip. Since my relatives live on the other side of the world, this makes it very easy for me to update them about what's going on in my life—and show off photos without having to lob off enormous emails, stuffed with unreadable attachments.
To get started, you're going to need photos, each with its own latitude and longitude coordinates. The easiest way to do this is by bringing along a GPS when you photograph, and mark each image with a waypoint or write the location on a notepad. If you're interested in doing large batches of photos, pick up a copy of O'Reilly's Mapping Hacks and learn more about cross-referencing GPX tracklogs with the EXIF timestamp of digital photographs. alternatively, you can adapt the technique described in "Where Did the User Click?" [Hack #11] , and use your memory and a few map clicks to find the coordinates of where your photos were taken.
However you assemble the metadata for your photographs, you'll wind up with a JavaScript object that probably looks like this:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
How Big Is the World?
If you wanted to make your own Google Maps server, how much hard drive space would you need?
Google Maps renders maps by stitching small images together. We seek to discover the storage capacity of such an image repository. By capturing and examining screenshots of Google Maps in action, we can estimate the map scale at each zoom level, which will give us an idea of how much space is necessary to store all the tiles for that zoom level. Finally, we can add the storage requirements for each zoom level and apply some simple rules of thumb to arrive at an idea of how much hard drive space is necessary to support a web mapping service such as Google Maps.
First, we need to discover the scaling factors used at each of the fifteen zoom steps. To accomplish this analysis, we use a tool called Art Director's Toolkit, which comes bundled with Mac OS X and which offers an overlay desktop ruler image for measuring pixel distances onscreen. In zoom levels 0 to 6, we measure the pixel length between the northeast corner of Colorado and the southeast corner of Wyoming. This distance is clearly marked on the map as a horizontal line, which makes measuring it easy. Figure 2-16 depicts zoom levels 0, 1, and 2, where the distances in question are 12, 24, and 48 pixels, respectively.
Figure 2-16: Zoom levels 0 through 2
In Figure 2-17, we see that, for zoom levels 3, 4, and 5, the same distances are 98, 196, and 394 pixels.
For zoom level 6, the distance between the northeast corner of Colorado and the southeast corner of Wyoming measures out at 790 pixels. Zoom level 7 was skipped because there was nothing to measure for it—smaller things were too small, and bigger things were too big. (Skipping it did not negatively impact the analysis.)
Figure 2-17: Zoom levels 3 through 5
In zoom levels 8 through 14, we measure the pixel length of the path from the intersection of Trenton Street and East 16th Avenue to the intersection of Verbena Street and East 16th Avenue in Denver, Colorado, which is within the metropolitan area closest to our previous locations. For zoom level 8, the distance is 9 pixels. For zoom levels 9, 10, and 11, the distances are 19, 37, and 74 pixels. The results are shown in Figure 2-18.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Mashing Up Google Maps
In music, when you create a new song by taking the melody from one song and the lyrics from another, it is called a mashup. A lot of times things go poorly, but now and then the results are stunning. What happens when you take pieces from two web sites and mix them together? You get a Web 2.0 mashup.
The Web is moving from a collection of disconnected web sites to a ubiquitous computing platform. This new reality is often referred to as Web 2.0. In the beginning, we had static web sites with a few links between them. This evolved into dynamic content and data-driven sites. The next step has been using the web as a platform.
eBay is a useful site for buying and selling trinkets, trash, or treasure. In that role, it is what might be called "Web 1.5." But eBay is also a platform. There is a whole ecology that has built up around eBay that uses the platform in ways that were not initially intended by the programmers.
Amazon and Google Search have also become platforms. Amazon, eBay, and Google (not to mention Flickr, del.icio.us, and many more) have created public Application Programming Interfaces (APIs) that allow anyone to mix and match information from one site with information from another.
The missing piece in the ecology of open web APIs has been location. Nearly everything we do, on the Web or off, has a location. Everything we touch, write about, read, think, or work on has to happen somewhere. Everything has a geospatial component. Perhaps the geospatial component of some things is irrelevant. Do you really care where you were when you remembered to add dish soap to your shopping list?
Yes! We are the species that looks for patterns, and where we are, and where we have been, is one of the strongest sources of pattern in our lives! We are able to learn huge amounts from rooting through other people's trash, er, treasure—and we can learn similar amounts by analyzing the debris of our passing as recorded in position.
At the Where 2.0 conference in San Francisco in June of 2005, Tim O'Reilly explained his fascination with Paul Rademacher's Housing Maps site (
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Hacks 17–28: Introduction
In music, when you create a new song by taking the melody from one song and the lyrics from another, it is called a mashup. A lot of times things go poorly, but now and then the results are stunning. What happens when you take pieces from two web sites and mix them together? You get a Web 2.0 mashup.
The Web is moving from a collection of disconnected web sites to a ubiquitous computing platform. This new reality is often referred to as Web 2.0. In the beginning, we had static web sites with a few links between them. This evolved into dynamic content and data-driven sites. The next step has been using the web as a platform.
eBay is a useful site for buying and selling trinkets, trash, or treasure. In that role, it is what might be called "Web 1.5." But eBay is also a platform. There is a whole ecology that has built up around eBay that uses the platform in ways that were not initially intended by the programmers.
Amazon and Google Search have also become platforms. Amazon, eBay, and Google (not to mention Flickr, del.icio.us, and many more) have created public Application Programming Interfaces (APIs) that allow anyone to mix and match information from one site with information from another.
The missing piece in the ecology of open web APIs has been location. Nearly everything we do, on the Web or off, has a location. Everything we touch, write about, read, think, or work on has to happen somewhere. Everything has a geospatial component. Perhaps the geospatial component of some things is irrelevant. Do you really care where you were when you remembered to add dish soap to your shopping list?
Yes! We are the species that looks for patterns, and where we are, and where we have been, is one of the strongest sources of pattern in our lives! We are able to learn huge amounts from rooting through other people's trash, er, treasure—and we can learn similar amounts by analyzing the debris of our passing as recorded in position.
At the Where 2.0 conference in San Francisco in June of 2005, Tim O'Reilly explained his fascination with Paul Rademacher's Housing Maps site (
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Map the News
See where it happened with BBC News and Google Maps.
Human beings have spent most of their time in small groups of 100-odd individuals, and our information-processing abilities came from those experiences, not from our current world. If we want to keep track of disturbances in Denmark, fog in Finland, elections in Istanbul, and war all over, we need tools to help us: assisted cognition.
At http://boneill.ninjagrapefruit.com/wp-content/bbc/newmaps/ you can see the locations associated with the last 12 hours of BBC news, as shown in Figure 3-1. As with most cartographic efforts, there is the nearly inevitable, but still regrettable, focus on just one place—so the last 12 hours of BBC news will generally be more interesting if you prefer news of the British Isles.
Clicking on the markers brings up an information window like that shown in Figure 3-2. This includes the lead from the story, as well as date and time information and a link to the full story. As we can see, human interest and soft news can make an appearance!
This hack is possible because, well, the BBC rocks. They have decided that their responsibility to the public trust means they need to open their content to the public. See http://backstage.bbc.co.uk/ for data and ideas so that you can "build what you want using BBC content." This is the heart of the Web 2.0 concept—the idea that open APIs and open formats allow us to make more use of and draw richer connections between the vast amounts of information that are already out there on the Internet.
Figure 3-1: Geolocations for the last 12 hours of BBC News
Figure 3-2: Not all geolocated news is created equal
In 2003, the BBC announced plans to open their archives of radio and television programs for non-commercial use. Its intent is good, but sadly there are issues that must be worked out. Ben Hammersley wrote a stirring call to action for the Guardian at http://www.guardian.co.uk/online/story/0,,1522351,00.html.
The archive, Ben writes, "is a vault of the most important public culture of the past three generations. It is a gift for the future that is so far-sighted, and so much a good thing, that it is the duty of the BBC and, especially, the government to follow through."
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Examine Patterns of Criminal Activity
Augment your local government's crime reports with Google Maps.
Chicagocrime.org (http://www.chicagocrime.org/), one of the original Google Maps hacks, is a freely browsable database of crimes reported in Chicago. It combines data that was screen scraped from the Chicago Police Department's Web site (http://12.17.79.6/) with Google Maps, enabling many new ways for Chicago residents to keep tabs on their neighborhoods and explore crimes reported throughout their city. The site lets you browse crime reports in many ways: crime type, street name, date, police district/beat, ZIP Code, city ward, and generic "location" (e.g., bowling alley, bar, gas station). Figure 3-3 sh