Google Maps Hacks
Google Maps Hacks By Rich Gibson, Schuyler Erle
January 2006
Pages: 366

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 shows a rash of peeping toms around residential Chicago, while Figure 3-4 shows the locations for bogus check reports. There's also a City map page at http://www.chicagocrime.org/map/ that lets you combine search criteria.
Figure 3-3: The most recent reports of illegal surveillance activity in Chicago
Figure 3-4: The most likely places to find bogus checks in Chicago
I developed Chicagocrime.org over a month's worth of nights and weekends in April 2005. Having gotten excited by the recently launched (at that time) Google Maps site, I spent a few evenings digging around Google's JavaScript and trying to embed custom maps into my own pages. After some hacking, I was able to display a custom map successfully. With my hacked-together map framework in place, it was just a matter of screen scraping the CPD's web site, geocoding each crime, and displaying the data. After Google released its official API at the end of June 2005, I updated Chicagocrime.org to make use of it.
Aside from displaying a custom Google Map with relevant crime data on almost every page, Chicagocrime.org uses the Google Maps API in a couple of innovative ways. One way of navigating crime data is by police district. Because some residents of Chicago may not know their assigned districts, I created a "Find your beat and district" feature—http://www.chicagocrime.org/districts/
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 Local Weather Conditions
Find out whether there's weather where you are.
It's a well-known fact that everyone likes to talk about the weather, yet no one ever seems to do anything about it. Seriously, though, whenever two strangers meet and make small talk, it's inevitable that the recent meteorological conditions will make an appearance in the conversation. The state of the weather outside today, whatever it turns out to be, is something we all have in common—we're all obliged to endure it or enjoy it—at least, those of us that go out of doors.
Naturally, it didn't take long for someone to set up a Google Maps site devoted to tracking the weather—and we don't just mean any old weather, we mean detailed weather data, including temperature, wind speed and direction, relative humidity, and daily rainfall. Dave Schorr's Google Weather Maps site, at http://www.weatherbonk.com/, collects meteorological data aggregated by Weather Underground and Weatherbug from thousands of personal weather stations across the world, and then plots that information in a rich Google Maps interface on the Web.
Figure 3-5 shows the default view of weatherbonk.com, centered on San Francisco, California. If, as chance would most likely have it, you're not in San Francisco, you can start by entering your location in the search box at the top of the page. Valid location styles take the form city, state, or city, country. U.S. ZIP Codes also work. In addition, you can overlay points from multiple locations by separating each query with a semicolon (;). For example, entering 33010;33446 will give you points along the southeast coast of Florida.
While a good number of international cities come up with results, you may need to be careful about what you type in here; for example, typing in "London, UK" returns nothing, while "London, England" returns what you would expect.
Also, at the time of this writing, Google only has detailed street maps for the U.S., U.K., Canada, and Japan. If you see broken image links in the background of the map, Google has not yet created street maps for your area. In this case, keep zooming out until the map appears, and/or click the Satellite button on the map to switch to the satellite view.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Track Official Storm Reporting
Follow the path of the latest hurricane on a Google Map.
Google Map hacking started for me in early March 2005, when I became aware of some of the great hacks that were already being created. My interest was particularly piqued after seeing the beta release of Adrian Holovaty's Chicagocrime.org web site, as described in "Examine Patterns of Criminal Activity" [Hack #18] . I immediately realized the myriad other applications for this new mapping technology. To be more precise, I determined that it would be beneficial to develop a storm-reporting mapping site, which you can visit today at http://www.stormreportmap.com/, as shown in Figure 3-7.
Figure 3-7: The weather on Google Maps
You can click on a marker to see more details. For example, Figure 3-8 shows a report of hail in Sioux, Nebraska.
Another interesting feature is the hurricane tracking maps. As shown in Figure 3-9 you can see the tracks of tropical storms.
Clicking on the marker icons gives you more information about the storm at that point. In Figure 3-10, we see that Irene has been bouncing between a tropical storm and a tropical depression.
The data source for the web site is the National Oceanic & Atmospheric Administration's (NOAA) National Weather Service (NWS) Storm Prediction Center (SPC), which can be found online at http://spc.noaa.gov/. One of the top products that the SPC maintains is their Storm Report tracker at http://spc.noaa.gov/climo/. This product takes reports from trained weather spotters, emergency and first responders, and local residents, and then maps them to an unattractive, static page. Moreover, the reports also don't give much in the way of comprehensible locations, aside from latitude/longitude coordinates, and the county and state where the storm was reported. Additionally, since each report is submitted into the database as a separate event, there are times when several tornado reports received are actually all from the same tornado. Due to these shortcomings in the original product, and because of its general popularity, I felt that my project might enhance the product's basic functionality.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Track the International Space Station
Track the International Space Station and the Space Shuttle in near-real time.
You can track anything on Google Maps—all you need is a source of data. Tom Mangan created his own site to track the Space Shuttle and International Space Station (ISS) at http://gmaps.tommangan.us/spacecraft_tracking.html.
The site tracks the location of the ISS and, when it is in orbit, the Space Shuttle, as shown in Figure 3-11. The excitement can come from being able to spot the Shuttle and ISS from the ground, and in watching on the map as they rendevous. When you first load the page you should get one or two markers, depending on whether the Shuttle is in orbit. If you leave the page open the markers leave a trail of where the ISS and Shuttle have been. Over the course of about 90 minutes (actually, 91.55 minutes for the ISS, according to the Wikipedia page at http://en.wikipedia.org/wiki/International_Space_Station), the characteristic sine wave shape of low Earth orbits appears. No, objects in space don't bounce around like tennis balls; this represents the effects of representing a three dimensional orbit onto a flat map. The first rule of cartography is that you always distort something!
Figure 3-11: Shuttle and ISS tracking, with an amusing note
Google's AdSense ads are often the funniest part of a page. Here we have a link to "NASA Space Shuttle for sale. Check out the deals now!" I don't think I want to buy an affordable spacecraft on eBay! Maybe in a few years.
Most of the work happens in the JavaScript in the site's autoUpdate( ) function. autoUpdate( ) is called as soon as the page loads.
	<body style="background-color: #000; text-align: center;"
	         onload="autoUpdate();">
The autoUpdate function uses the GXmlHttp class from Google Maps to fetch the iss.js file from the server. You can take a look at the file at http://gmaps.tommangan.us/iss.js.
	-48.6;-11.7;369.8;-51.6;-31.9;291.1
This shows the latitude and longitude of the ISS first, and then that of the shuttle. The code reads the file, then splits the results into the array
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Witness the Effects of a Nuclear Explosion
Sometimes a map can reveal truths we'd rather not know.
For over 50 years, the human race has lived under the shadow of the threat of nuclear war. Eric A. Meyer's HYDESim (High-Yield Detonation Effects Simulator) web site, which uses Google Maps in a somewhat novel way to illustrate the blast effects of a nuclear detonation. You can see the results for yourself at http://meyerweb.com/eric/tools/gmap/hydesim.html. Figure 3-12 shows the default view, which illustrates the effect of a 150 kiloton explosion at ground level in downtown Manhattan.
Figure 3-12: Depiction of the blast wave of a 150-kT nuclear explosion in downtown Manhattan
The blast effect of a nuclear explosion is usually reckoned in terms of overpressure, which is a measure of how much force is exerted on people and buildings at a given distance away from ground zero. On the map, this is shown as four concentric rings of decreasing intensity, which spread outward from the hypothetical explosion site, representing overpressures of 15 psi, 5 psi, 2psi, and 1 psi, respectively. The display on the left shows the blast radius for .25 psi overpressure as well, although this ring is not shown on the map.
What exactly do these figures mean, though? The descriptions shown in Table 3-1 are taken from section 5 of the Nuclear Weapons FAQ at http://nuclearweaponarchive.org/Nwfaq/Nfaq5.html.
Table 3-1: Destructive effects of atmospheric overpressure
Overpressure
Structural effects
Human injuries
1 psi
Window glass shatters.
Light injuries from fragments occur.
3 psi
Residential structures collapse.
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 a Place to Live
Why slog through endless listings of apartments that all look the same, when you can pick and choose based on where you actually want to live?
Finding a place to live, particularly in large cities, can be a huge pain. Locating a place at a price you can afford is enough of a challenge, but, even when you can locate such places, they're often not situated where you actually want to live. Real estate and rental listing sites like Craigslist.org go a long way towards easing this pain by offering searches against listings based on keywords and price brackets, but often even the search results themselves are still daunting. Where the heck are all these places? How close are each of these apartments to the grocery store? To public transit? To my friends' houses? The listings often include neighborhood names, or even street addresses or nearby intersections, but if you're not particularly familiar with the area, these names might not mean anything to you.
Paul Rademacher's HousingMaps site offers an inventive start on a solution to this problem: take one part Craigslist.org real estate listings, one part Google Maps API, and stir!
The front page of HousingMaps, which you can find at http://housingmaps.com/, shows a Google Maps view of the United States and Canada, as seen in Figure 3-13. The green icons on the map mark many of the major urban areas served by Craigslist, and clicking one opens a call-out, from which you can select real estate for sale, rentals, rooms for rent, and sublets or temporary housing for that city.
If you find this view a bit confusing—or find the icons hard to click, as in the northeastern United States, where the icons are bunched a bit close together—then you can select the metropolitan area of your choice from the drop-down box at the top left, and then use the links above to narrow your search. (Alternatively, you can recenter with a mouse drag or double-click, and then zoom in! This is Google Maps, after all.) Finally, another drop-down box at the top allows you to indicate price ranges of properties to show on the map.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Search for Events by Location
Events listed in the EVDB event database can easily be plotted on a Google Map.
Using a generic search engine isn't a good way to find out about events such as musical performances or garage sales. You can't specify that only event descriptions are wanted, and even if you could, the results aren't displayed in a way that organizes them usefully in time and space.
Wouldn't you like to be able to type keywords ("U2", "pug meetup", etc.) into a specialized event service, and get back not only a list of textual descriptions, but also a map showing event locations and a calendar highlighting event dates? Well, that's what EVMapper does. You can try EVMapper for yourself at http://mapbureau.com/evmapper/. Figure 3-15 is a screenshot of the results of the "pug meetup" search.
Figure 3-15: Pug meetup locations
You can click on a map dot, or an event listing, or a highlighted calendar date, and details about the event at that place or time will be displayed. If there is more than one, a list is displayed instead. Whenever an event is selected, and however the selection took place, its location will be marked on the map by the big balloon and its date will be marked by a little red square on the calendar. You can also click your way through the events in time.
EVMapper is a mashup of two services: EVDB and Google Maps. EVDB (http://evdb.com) is the Events and Venues Database, a free site that allows anyone to submit or search for events. An EVDB search displays a list of events; events can also be organized into personal calendars. However, maps are not currently part of the experience at the EVDB site.
EVDB provides a RESTful API to the event database (http://api.evdb.com). When a user enters a query into EVMapper, an /events/search call is made to the API; for example:
	http://api.evdb.com/rest/events/search?app_key=…&keywords=pug+meetup
The XML returned by EVDB contains descriptions of the matching events. The descriptions specify place by name (e.g., city, state, and sometimes ZIP Code or street address), not latitude/longitude, so EVMapper needs to do the geocoding. EVMapper implements the simplest possible geocoding method, which is adequate to demonstrate the idea of event mapping: it looks up city/state in a GNIS database covering the United States only. The Geographic Names Information System is the official repository of place names in the United States. You can query the GNIS 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!
Track Your UPS Packages
With Google Maps and a simple Greasemonkey user script, you can watch your UPS packages travel across the country.
Anyone who's received a package delivered by UPS, or any other large shipping company, probably has had the experience of wondering where the heck the package is right now, and when exactly it's going to arrive. By entering the package's tracking number into a form on the UPS web site, you can get back a list of the cities which the package has traveled through to date. Of course, this is enough information to allow us to visualize the package's progress on a map!
As usual, the trick of mashing up Google Maps with information from another site, such as that from the UPS tracking form, involves a bit of contortion, to get around security restrictions in the browser. One solution to this problem (at least for Mozilla Firefox users) is to use a Greasemonkey user script to modify the contents of a web page to include a link to a map of the things on that page. The Greasemonkey approach [Hack #27] is exactly the one taken by Matthew King, when he decided he wanted to visualize the path traversed by his new laser printer, on its way from the warehouse to his hometown.
First, you'll need to be running Mozilla Firefox. You'll also want to install the latest version of the Greasemonkey extension from http://greasemonkey.mozdev.org/, if you haven't done this already; see "Add Google Maps to Any Web Site" [Hack #27] for more information on how this works. To install the UPS tracking user script, visit http://www.thrall.net/~mking/maps/upstrack.user.js in Firefox, and then select Tools → Install User Script from the menu bar. A confirmation window will pop up, in which you can simply click OK.
Now you're ready to track your UPS packages! Visit the UPS package tracking form at http://www.ups.com/content/us/en/index.jsx, enter a tracking number, click the checkbox to accept the terms and conditions of use, and then click the button marked Track. A summary page will load, with a "View package progress" link. Click this link as well. You should get a results page that looks something like Figure 3-16. This particular example shows the course of a box of O'Reilly's
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Follow Your Packets Across the Internet
Ever wonder where your network traffic goes when you visit a site on the 'Net?
Not long after the Internet began to be widely used in our society, a new word began to gain currency among the public to evoke the experience of being able to find information and communicate with people from all over the globe, and that word was cyberspace. In fact, the word "cyberspace," taken from the term cybernetics, a technical term for human-computer interfaces, has been so overused that it comes across as trite or hackneyed today. All the same, the word conjures up an image of sweeping digital vistas, waiting to be explored and homesteaded, and so has a great deal of potency—which is probably why the word became a cliche in the first place.
The fact, however, is that the Internet works so beautifully and, usually, so transparently, that most people don't take the time to consider that cyberspace and meatspace (as we hackers sometimes jokingly refer to the Real World) are actually connected. Obviously, every web server, DSL router, cable modem, dial-up service, and so on, is located somewhere on the planet. But who knows where?
As it happens, the Whereis service at http://www.parsec.it/whereis/ knows where Internet addresses are hosted in the real world, sometimes with astonishing accuracy. The front page of the site, clearly modeled after Google's, offers a simple search box, where you can type in an Internet domain name or an IP address in dotted-quad format (e.g., 192.168.1.1). Clicking the locate button takes you to the view shown in Figure 3-18, with a Google Map showing a marker over the most probable physical location of that Internet address. Clicking on the marker pops up some basic information about the address, including the country and locale that it's believed to be physically located in or near.
Whereis uses the standard Google Maps API to display the map on the results page. Embedded within a JavaScript block on the results page is a call to the GMarker( ) constructor, which specifies the physical coordinates of the Internet address and generates the marker that you see on the map.
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 Google Maps to Any Web Site
Greasemap adds informative Google Maps to almost any page on the Web.
There are lots of sites on the Web that don't have maps but could really use them. Any web page with an address or a set of latitude and longitude coordinates is a candidate for a potentially useful map. Let's say, for example, that you want to visit O'Reilly's global headquarters to purchase the next hot Animal book straight from the bookstore in the reception lobby. You could go to http://www.oreilly.com/oreilly/contact.html and get the address, but what good does that do you? At the very least, you'll have to copy the address to your clipboard, and then go to http://maps.google.com/ in another browser window, paste the address in there, and so on. Isn't there some way your web browser could just do this for you?
As it happens, there is a way—if you're running Mozilla Firefox. Firefox supports an extension called Greasemonkey, which allows custom JavaScript-based user scripts to, well, monkey with the contents of any page you view in your browser. As you can imagine, there is a wealth of possibilities inherent in the Greasemonkey concept.
Vinq.com's Greasemap is one such user script for Greasemonkey. Greasemap augments any web page you visit, by searching the page for street addresses and clearly marked geographic coordinates. If it finds any, Greasemap provides a clickable message bar across the top of the page, notifying you that a map is available. Clicking on the message bar adds an IFrame to the top of the page, in which a Google Map is loaded, displaying all the locations found on that page.
The maps from Google remain interactive; you can zoom in, pan around, and so on. The map will be one wide map if there are multiple locations found, or two smaller maps—an overview map and a zoomed in map—if there is just one location found on the page.
Installing Greasemap takes a few short steps and should be almost painless.
  1. Download and install Greasemonkey (http://greasemonkey.mozdev.org/). When you first try to install Greasemonkey, you may see a thin bar at the top of Firefox that says "Firefox prevented an extension from loading." Click the button at the right side of that bar, then "Allow extensions from that site." Once you've done this, try installing Greasemonkey again; it should work the second time around.
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 That, Exactly?
Explore the size of geographic regions in terms of those you already know.
A Google search for "roughly the size of" returns 398,000 results. Certainly this suggests that, when it comes to visualizing the size of faraway places, we feel the need to refer to the unknown in terms of the familiar. Take this newspaper quote, for example:
…when the Amazon shrank a record 11,200 square miles, an area roughly the size of Belgium, or the American state of Massachusetts….
I read that and get a vague sense of confusion and think, "Wow, I bet the people in Belgium and Massachusetts know what that means, but I sure don't." There's more:
"Huge iceberg menaces Antarctica…roughly the size of the island of Jamaica." (http://www.theregister.co.uk/2005/05/20/iceberg_penguin_menace/)
"The largest-known iceberg was from this region. It was roughly the size of the state of Rhode Island." (http://www.factmonster.com/ipka/A0781668.html)
"Months later, after I discussed what I had seen with the oceanographer Curtis Ebbesmeyer, perhaps the world's leading expert on flotsam, he began referring to the area as the 'Eastern garbage patch.' But 'patch.' doesn't begin to convey the reality. Ebbesmeyer has estimated that the area, nearly covered with floating plastic debris, is roughly the size of Texas." (http://www.naturalhistorymag.com/1103/1103_feature.html)
A search for "roughly the size of" reveals interesting things. The fact that the writer needed to find something, anything, to use to provide a measure of spatial context hints at something odd and interesting. An "Eastern garbage patch…roughly the size of Texas"? The image is vivid.
The statement "roughly the size of…" demands the ability to compare the unknown with a known quantity. At http://www.mappinghacks.com/projects/gmaps/size_of.html you can select the outline of a state or country and pin it onto the map. Pick the shape from a drop-down box then scroll around on the map until you find a familiar place and click. Figure 3-25 shows an outline of Pennsylvania on top of Hungary.
State boundaries can have an historical basis, but often are rather arbitrary. There is no particular reason for us to respect the work of our forebearers, and with Google Maps we don't need to! Figure 3-26 shows an outline of the state of Delaware, rotated 90 degrees clockwise and pinned over the San Francisco Bay area.
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 4: On the Road with Google Maps
By now, you should be familiar with the basic use of Google Maps for finding driving directions. However, the flexibility of Google Maps offers plenty more opportunities for figuring out how to get from point A to point B. We'll see that Google Maps can assist you in finding the best gasoline prices, avoiding traffic congestion, and even avoiding the use of an automobile altogether!
In this day and age, one of the most useful tools of the digital cartographer is her Global Positioning System, or GPS, receiver. We're also going to explore several useful combinations of GPS and Google Maps, including loading routes from Google Maps into your GPS receiver, plotting your travels from the GPS receiver's tracklog within Google Maps, and how to use your GPS to make Google Maps of local wireless network coverage.
As a bonus, we'll also see how Google Maps saved one man from an expensive traffic fine!
Drive your mouse for cheaper fuel—and then catch a movie.
My friends in construction spend a lot of time driving up and down Highway 101, and they all know where the cheap gas is. I spend my time sitting in front of a computer, but thanks to http://www.ahding.com/cheapgas/,I also know where the cheap gas flows.
The Cheap Gas site in Figure 4-1 uses data from http://www.gasbuddy.com/, which aggregates user reports of gas prices so that everyone can benefit. You can also contribute to the Gas Buddy web site by becoming one of their volunteer spotters, thus gratifying your natural human desire to tell other people something that they don't know.
Figure 4-1: Where are the deals?
After you pick a city, the site lists gas stations on the side bar and markers on the map. The green icons represent the lowest half of gas stations by price and the red icons are the high half. As shown in Figure 4-1, each station has a marker with more information.
What is interesting about this example is the integration with http://www.gasbuddy.com/. GasBuddy.com provides the database of cheap gas, but is not run by cartographers, so Ahding.com was able to create the now-classic mashup.
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 29–41: Introduction
By now, you should be familiar with the basic use of Google Maps for finding driving directions. However, the flexibility of Google Maps offers plenty more opportunities for figuring out how to get from point A to point B. We'll see that Google Maps can assist you in finding the best gasoline prices, avoiding traffic congestion, and even avoiding the use of an automobile altogether!
In this day and age, one of the most useful tools of the digital cartographer is her Global Positioning System, or GPS, receiver. We're also going to explore several useful combinations of GPS and Google Maps, including loading routes from Google Maps into your GPS receiver, plotting your travels from the GPS receiver's tracklog within Google Maps, and how to use your GPS to make Google Maps of local wireless network coverage.
As a bonus, we'll also see how Google Maps saved one man from an expensive traffic fine!
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 the Best Gasoline Prices
Drive your mouse for cheaper fuel—and then catch a movie.
My friends in construction spend a lot of time driving up and down Highway 101, and they all know where the cheap gas is. I spend my time sitting in front of a computer, but thanks to http://www.ahding.com/cheapgas/,I also know where the cheap gas flows.
The Cheap Gas site in Figure 4-1 uses data from http://www.gasbuddy.com/, which aggregates user reports of gas prices so that everyone can benefit. You can also contribute to the Gas Buddy web site by becoming one of their volunteer spotters, thus gratifying your natural human desire to tell other people something that they don't know.
Figure 4-1: Where are the deals?
After you pick a city, the site lists gas stations on the side bar and markers on the map. The green icons represent the lowest half of gas stations by price and the red icons are the high half. As shown in Figure 4-1, each station has a marker with more information.
What is interesting about this example is the integration with http://www.gasbuddy.com/. GasBuddy.com provides the database of cheap gas, but is not run by cartographers, so Ahding.com was able to create the now-classic mashup.
What causes gas price variations? An interesting project in geospatial analysis would be to see if one could draw any conclusions about why there is such variation in prices from station to station. Overlaying different thematic layers and doing calculations based on multiple data sets is exactly what a Geographic Information System (GIS) is all about, but Google Maps has shown that there has been an enormous demand for an easy-to-use "put a push pin on a map" solution. That is now a solved problem!
Once you get your fuel price woes straightened out, you can click on the Movies link at http://www.ahding.com/movie/ and use the same basic interface to query the Internet Movie Database (http://www.imdb.com) to check out local movies.
Another low-cost-gasoline solution is GasWatch by Adrian Gonzales, which is available from http://www.widgetgallery.com/view.php?widget=36500. This is a widget that will run under Konfabulator for Windows and Mac OS X (the grass is greener on both sides) and show you the best prices for gas. "GasWatch shows you the lowest priced gas in your ZIP Code. It also provides a handy button to show a map to the gas station. Maps for Mac users provided by Google Maps."
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Stay Out of Traffic Jams
A few Google Maps mashups to keep you and your car out of trouble.
According to statistics published by the BBC in 2002, there are nearly half a million traffic jams in Britain every year—or more than 10,000 a week—and those numbers were on the rise. A quarter of Britain's main roads are jammed every day, and nearly 1 in 4 residents of the U.K, have to contend with heavy automobile traffic daily. In our car-obsessed United States, automobile commuters spent an average of 47 hours delayed by traffic congestion in 2003 alone, according to estimates published by the Texas Transportation Institute. In the ten largest metro areas in the States, that figure goes up to an average of 61 hours a year. That's two and a half whole days out of every year, spent by the average driver, just sitting in the car, idling in bumper-to-bumper gridlock!
Fortunately, the hackability of Google Maps offers hardy urban dwellers superior access to timely information in this fast-paced era! Almost as soon as Google's flashy road maps hit the Web, hackers went to work plotting out the miasma of traffic congestion that plagues the lives of so many in the urbanized western world.
The best Googlified traffic maps of the States come from the Google-Traffic. com Traffic-Weather Maps site at http://supergreg.hopto.org/google-traffic.com/. Using RSS from the Traffic.com web site, "Super" Greg Sadetsky has assembled an informative service that reports the locations of traffic conditions in major U.S. cities. From the front page, you can select your city of interest, and click the Go! button to be taken directly to the map. Figure 4-3 shows the current traffic conditions in Philadelphia.
Figure 4-3: A Google-Traffic.com traffic map of Center City, Philadelphia
Custom icons show the type of delay—either construction or some kind of incident—and the color of the icon indicates the severity of the delay, from yellow to red. Clicking on any of the icons loads a callout that displays the details of the traffic delay. Miraculously, the Schuylkill Expressway (I-76) is clear this morning—but it's early yet, only about 6:30 A.M.—while the Broad Street exit of I-95 should plainly be avoided, especially later this evening when baseball fans will flock to Veterans Stadium to watch the home team lose to the Rangers.
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 Public Transportation
Finding your way around local public transit just got a lot easier.
You have an appointment in town somewhere, and you've just discovered from "Stay Out of Traffic Jams" [Hack #30] that it's definitely not worth driving this morning. You fire up your local public transit authority's web site, download their sketchy schematic map of the subway or bus system, and then discover to your chagrin that the map gives you no idea of which stop on which route is actually closest to your destination. Does this sound familiar? If the Google Maps hackers get their way, your experience will soon be a thing of the past.
As of this writing, Google Maps–enhanced public transportation maps are only available for a few cities in North America. Here's a rundown of what's available.
The first stop on our tour of Google Maps transit mashups is David Pritchard's Vancouver Transit Map for the public transportation system in Vancouver, BC. The Vancouver Transit Map lives on the Web at http://www.david.enigmati.ca/maps/transit.html. As you can see from Figure 4-9, the site uses Google Maps polylines to depict the major transit routes in town.
Figure 4-9: Public transit in Vancouver, BC
The transit line stops are depicted with circles, which open an info window showing the name of the stop and the intersecting bus lines. The text labels showing the names of major stops at different zoom levels are also clickable, and make for a nice touch in terms of the map's readability.
Matt King's Boston Subway Station Map at http://www.thrall.net/maps/mbta.html takes something of a similar approach, as you can see in Figure 4-10. Instead of the station labels on the map, along the top we get a row of color-coded drop-down boxes, organized by subway line, to help find individual stations.
Clicking any of the station markers opens an info window with the station name, street address, and navigational links. The "To here" and "From here" driving directions links are pretty self-explanatory, but the "Zoom in" and "Zoom out" navigation links are special. If the map is zoomed out, clicking "Zoom in" will cause the map to iteratively zoom in, one level at a time, on a delay interval, so that you can situate the subway stop in the larger geographic context of Boston. Once zoomed in, the "Zoom out" link performs the reverse operation. This progressive zoom-in/zoom-out is referred to by digital cartographers as
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Locate a Phone Number
Perform reverse lookups with Google Phonebook and Google Maps.
Have a phone number, but you don't know where it originates? You can use Google to get an address, and then Google Maps to pinpoint it. Your search engine is a phone book? Why not? Phone numbers are just another thing that can be searched on!
When you enter a phone number into the search box on http://google.com, the first link is to the Google Phonebook (assuming that the number is found). For example, doing a search on the U.S. phone number (707) 827-7000 brings up the results shown in Figure 4-13. The Google phone book is very forgiving. You can search for 707 827-7000 or 707-827-7000 or even 7078277000 and Phonebook will still work.
Interestingly enough, you can't search for a phone number directly through the Google Maps search box: you have to go through the regular Google Search first!
Figure 4-13: Google Phonebook results for (707) 827-7000
The Google Phonebook is mapping-service agnostic, showing links to this address in Google Maps, Yahoo! Maps, and MapQuest. If you click on the Google Maps link, you can do a local search for something common, such as pizza, and then click on "Link to this page" near the top right of the page to get a page like Figure 4-14.
The point isn't to get information on pizza, but to show that when you click on "Link to this page," Google Maps loads the URL for the current map in your browser. That URL includes the latitude and longitude of the center of your search area as the sll parameter, which stands for search lat/long. Look at the address bar in Figure 4-14, and you can see the URL query string ?q=pizza&sll=38.411170,-122.841720. So, phone number (707) 827-7000 is located at 38.411170 N, 122.841720 W. That location isn't perfect, but it is pretty darn good. See "Inside Google Maps URLs" [Hack #7] for more on the structure of Google Maps URLs.
Figure 4-14: Pizza near (707) 827-7000
Another thing to note about that original Google search for the phone number in Figure 4-13, is that a search for a phone number also does a standard Google search. This can be interesting because it pulls things up in a new way. The first Google link for O'Reilly's phone number is a Road Warrior's Christmas list. Who would have thought that?
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Why Your Cell Phone Doesn't Work There
Trouble getting a signal? Google maps and the FCC database can help.
I live almost in the shadow of a 30.2-meter cell phone tower, and I have to go out on the porch to get decent reception. What is up with that? I know the exact height of the tower, thanks to Mobiledia. You can go to its site at http://www.cellreception.com/towers/index.html and browse for cell towers by city or state. When I look up Sebastopol, California, I get the map in Figure 4-15.
I live near the S in Sebastopol, so you'd think I'd have pretty good coverage 2.5 blocks from the tower. Clicking on the overlay marker brings up information on the owner of the tower, as shown in Figure 4-16. So my problem appears to be that there is a tower, but my cell provider doesn't have gear up there.
Figure 4-15: Cell towers near Sebastopol, CA
You can click on the overlay marker because marker labels are HTML and support links. Mobiledia defines marker text with this line of code:
	var html="<h1><a href='http://www.cellreception.com/towers/details.php?id=" +
	id + "'>" + name + "</a></h1><br>" + address + "<br>" + city + ", " + state;
This builds a URL that calls a script on its site with more details. This is an example of how you can include links and arbitrary HTML in pop-up markers. Mobiledia uses the FCC database of antennas, and as explained on the site:
The FCC does not require every antenna structure to be registered, and the map may not list all the towers in the area. Additionally, many carriers have sold their tower assets to third party companies, and leasing agreements are unknown. If this is the case, the best way to determine carrier coverage is by reading comments in the local area.
So it is possible that my provider rents space on the tower, but since the best way to determine coverage is to read the comments, I think it is safe to just assume that my calls don't go to the most convenient tower.
On the right sidebar is a "Cell phone reception search." Enter a ZIP Code and it pops up a reader forum on reception, or in reality more likely the lack of reception. You can also search for dead spots and add your own reviews.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Publish Your Own Hiking Trail Maps
Tell your own stories with a mix of social software and cartography.
We've all found ourselves climbing through hillside brambles on a hot sunny day thinking, "That's the last time I trust that trailhead pamphlet." Or worse, wanting to show a friend a special place you found on a hike a few months ago but now can't quite place.
If you're a hiker, mountain biker, rock climber, weekend warrior, amateur geologist, scout troop leader, endorphin junkie, equestrian, pedestrian, rock climber, birder, or simple romantic, then have we got a hack for you! The site, which lives at http://BayAreaHikingTrails.ning.com, looks like Figure 4-17.
Bay Area Hiking Trails (BAHT), written by Saumi Mehta and May Woo, allows you to capture and publish your trail maps with comments, GPS tracklogs, and photos. Even better, you can easily overlay your GPS tracklogs on Google Maps via the API and provide a visual representation of your hike, bike, or ride alongside all these other goodies. But that's only the start. You can also offer these annotated trail maps to friends or strangers for rating and reviewing. You can even look for new hiking friends and fellow enthusiasts. How's that for social?
Figure 4-17: Bay Area Hiking Trails
All right, so that may not be enough. Let's take it one step further. No single social map can cover all scenarios of what you might want to do with it. With just a little bit of PHP knowledge, BAHT enables you to easily change or extend the user input forms so that you can record your own specialized data: birds seen, bikers met, geocaches planted, or geocaches found. You can also go further and change the HTML layout, add new features, or introduce new kinds of objects for your users to edit. Perhaps you are employed by a local parks service to identify invasive plant species and want a new kind of form input to describe those. Or you're a mountain biker who wants to have a slightly specialized social mapping application to document the rockiness, steepness, or exposure of certain trails.
BAHT is extensible for such uses because it is built on the Ning Playground, which is a free online system that enables you to clone, mix, and run fullblown social web apps like BAHT without worrying about a bunch of pesky details. The Ning Playground handles user account management, system administration, hosting, and bandwidth nightmares, not to mention the tedium of performance and scalability issues.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Load Driving Directions into Your GPS
From Google straight to your Global Positioning System receiver, thanks to GPSBabel.
GPSBabel (http://www.gpsbabel.org) makes it possible to convert driving directions from Google Maps into various formats usable by other software and devices. This is possible because Google encodes the coordinates of the entire route in the JavaScript that is sent to the Google Maps client and used to generate the route that is put on the map.
The first step is, of course, to get Google Maps to make some driving directions. We'll use one of the examples given on the Google Maps home page. Enter "JFK to 350 5th Ave, New York" and hit the Search button. After a short calculation, a map like that in Figure 4-18 appears, with the route highlighted.
Figure 4-18: Directions from JFK to Fifth Avenue
Now, we need to get the output into a predictable format. To do that, we first need a URL that contains everything we need to recreate our route. Fortunately, Google provides a tool to do just that! Click "Link to this page." The displayed map won't change, but the URL in the address bar will contain your query and the parameters needed to return to this map at this zoom level.
The last step is to modify that URL to output the JavaScript that the Google Maps client uses internally. To do that, just add &output=js to the end of the URL in your address bar and hit Enter. Your URL will look like this (but all on one line):
	http://maps.google.com/maps?q=jfk+to+350+5th+ave,+new+york&spn
	   =0.103861,0.199934&hl=en&output=js
The observant reader will note that the instructions "JFK to 350 5th Ave, New York" are included in that URL, with spaces having been replaced with plus signs. With this information you can skip the steps of looking up an address, clicking on "Link to this page," and changing the URL to include &output=js, and instead just enter the URL of the JavaScript page straight into your browser. Here is a link to the page containing the points for directions from JFK to San Francisco International Airport the hard way:
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 Driving Directions for More Than Two Locations
Going from here to there is okay, but going from here to there to another there to here is better.
In "Load Driving Directions into Your GPS" [Hack #35] we saw how to compute a route and load it into a GPS. The hack showed how to directly create a URL that will fetch the Google Maps file that contains the route points. GPSBabel can parse the points out of a route file and you can do whatever you would like with this information.
This suggests a script that takes a list of locations that Google can understand and then generates driving directions between each point. In addition to normal locations such as "San Francisco, CA to Denver, CO," Google Maps can generate driving directions based on latitude and longitude. The results of searching for directions from 38, -121 to 39.526421, -119.807539 are shown in Figure 4-19.
Figure 4-19: Directions from latitude/longitude to latitude/longitude
Lat/long routes don't always work. There are some places that are just a bit too far off of the beaten track for road-based routing to be effective. If you try 38, -121 to 39.731482, -119.53537, you get "We could not calculate driving directions between 38, -121 and 39.731482, -119.53537." Since 38, -121 worked in the first example, Google must have a problem with 39.731482, -119.53537. A glance at Figure 4-20 shows that Google should be forgiven for this routing difficulty. Apparently the engineers didn't anticipate helicopter-based mountain-top expeditions.
But lat/long–based directions work often enough to be interesting. Great, but why would you want to get driving directions for multiple points or for lat/longs? Let's say you want to drive from San Francisco to Denver; you can generate the route in Figure 4-21 with the query SFO to DEN, using an airport-to-airport search. Why do you need more than one set of directions?
You've got everything you need—1,299 miles, and you are there. But it turns out you want to stop in Moab for some of that Slickrock action. You can't (yet) enter a request to Google for multipart driving directions, such as
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
View Your GPS Tracklogs in Google Maps
Plotting your GPS tracklogs on Google Maps allows others to see where you've been.
Sharing tracklogs and waypoints from your GPS receiver became a lot easier with the invention of the GPX format, which is an open XML standard that encodes your GPS wanderings to a file readable by many applications. The best waypoints are pubs—so why not plot them on Google Maps, as in Figure 4-22?
Figure 4-22: Some waypoints of London pubs, shown in Google Maps
You can go to http://www.tom-carden.co.uk/googlegpx/ and upload your own GPX format file. Any waypoints appear as marker pins, and the start and end of tracks will be marked with pins, as shown in Figure 4-23.
Figure 4-23: A bit of a "derive" captured on the GPX viewer
There are several ways to process a GPX file into something Google Maps will understand, and we demonstrate two methods here. Using server-side processing, you upload the file from your browser and process it on your server (in this case using Ruby) and return a script that displays the data. Alternatively, you can put the GPX onto your own server and use some JavaScript to open it, process it on the client side, and pass it to Google Maps. The usual caveats for passing information around in a browser apply—there are restrictions on what scripts are allowed to access—but old friends like the iframe element and new friends like XMLHttpRequest can help us here.
No matter what method you use to process the GPX data, a GPX file will typically contain thousands of points—far too many for Google Maps to handle. Why is this? When you display polylines in Google Maps, your vectors are rendered into an image file on Google's servers. The more points, the more time it takes to generate the images. Except this isn't the whole story—Google only does this if you aren't using Internet Explorer. IE has a built-in vector language called VML, which renders the vectors very quickly in the browser.
Being fans of Firefox and Mozilla, for us it wasn't good enough to rely on IE. Therefore we thought up a way to selectively choose which points to display so we didn't have too many, yet had enough to show the route without slowing Google down. A seemingly obvious solution would be to simply drop every fifth point to reduce the number of points by 20%—but the problem is that one of those ignored points might be the crucial part of a turn or otherwise cause distortions of the route.
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 Your Wardriving Expeditions
Found Wi-Fi nearby? Put it on a map!
My interest in Wi-Fi is what got me started with GIS. I had been following the early 802.11 devices and was psyched to read about new modern and cheaply made wireless equipment in the news—and then actually see them on the shelves of various stores. Businesses of all sizes and millions of households started buying and installing these devices all over the place. I wondered where these things were being installed, and just how many were around.
Not long afterwards, I learned that there were people who would go out in their cars with GPSs and laptops, recording the locations of these wireless signals. These wardrivers, I learned, weren't breaking into these networks, but were comparing findings such as the funny names for some of the networks and the locations of the increasingly popular local wireless hotspots. I figured I had to try this out, and after about five minutes, I was hooked.
I was still curious about what my findings looked like. I had to figure out not only how to plot them, but also how to plot them on a map and on the Web. After a while, and with another curious person, Eric Blevins, we put together http://WiFiMaps.com.
WiFiMaps.com is a web-based geographic map of where Wi-Fi has been installed. The locations are updated by the users, who upload their wardriving scans of various areas. In turn, the site uses TIGER, Mapserver, and a host of other open source and otherwise free tools to plot street-level maps of Wi-Fi installations for those who wonder.
You too can do the same thing—and not just the wondering part, but also the where part. We'll do some wardriving and use a PHP script to parse the data found, and then plot the Wi-Fi spots on Google Maps.
For collecting Wi-Fi data, I generally use Netstumbler, available from http://www.netstumbler.com, which is popular among wardrivers. For free 'nix operating systems, Kismet (http://www.kismetwireless.net/) is the tool of choice, while on Mac OS X, there's both MacStumbler (http://www.macstumbler.com/) and KisMAC (http://kismac.binaervarianz.de
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Track Your Every Move with Google Earth
Ever wanted to have your own spy in the sky watching your every move, tracking you wherever you go?
Google Earth, formerly known as Keyhole, is the desktop-based big brother to Google Maps, offering 3D overviews of major cities, mountains, and other terrain, as well as local businesses and information, driving directions, and maps. Its features are far too numerous to mention here, but you can find out more and download a free version at http://earth.google.com/. Tragically, although it's based on the OpenGL standard, Google Earth is, as of this writing, supported on Windows only.
One of Google Earth's most interesting features is the ability to bookmark a particular view of a place or places, and then export that view to other Google Earth users via the Keyhole Markup Language (KML) format. The XMLbased KML format is good for adding static content to Google Earth (e.g., bridges, monuments, or buildings), but how do we map things that move?
Fortunately, Google Earth has something called a Network Link, which we'll look at a bit more in a second. The upshot is that we can use it to read in a .kml file that holds our position every few seconds. We also have a GPS system that updates our position every few seconds. The hack we're going to attempt is to constantly get the values from the GPS system into the .kml file. This is surprisingly easy to do on Linux, but we're running Google Earth on Windows, where things are slightly more, er, entertaining.
First, the tools we're going to use: Google Earth (and its Network Link feature), Firefox, one Garmin GPS receiver with a serial cable, a copy of Garnix for MS-DOS, two .bat files, ping, possibly some sticky tape, string, and a bit of luck. We'll talk about the other bits of software, like GPSBabel, but even if you don't have all this stuff—i.e., you have a different brand of GPS receiver—there should still be enough here to get you hacking around any problems.
Let's have a closer look at the .kml file we're going to be creating. Start up Google Earth, zoom into someplace near home, and press Ctrl-N to add a new Placemark. Call it something useful like "Me" and click OK. The Placemark will appear on the map, as well as in the Places section over on the left. Rightclick on the Placemark and select Save As. Save it as
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Ghost in Google Ride Finder
Generate street maps from Google's real-time taxi-mapping service.
One of the first Google Map Hacks was released by Google itself. The Google Ride Finder is ostensibly a mapping service to find nearby taxis and airport shuttles in major metro areas. While it's useless for getting a ride with these centrally booked services, it really functions as a very engaging advertisement for these companies. (And, while we're at it, don't we actually need the public transit Google Maps Hacks extended for live updates for sustainable transport alternatives?)
The real appeal is how Google Ride Finder demonstrates the use of realtime, updating spatial data. The immediacy of the Web, combined with geo visualization, has powerful possibilities. In this hack, that live data will be repurposed to reveal the street map "ghost" of airport shuttles and taxis, producing raw data that might be consumed by grassroots mapping projects such as OpenStreetMap ( http://www.openstreetmap.org/).
The Google Ride Finder lives at http://labs.google.com/ridefinder. The initial view shown in Figure 4-26 is of North America, with push pins marking the areas for which they have data.
Figure 4-26: Ride Finder home page
If you zoom in to Chicago, you'll get a view like Figure 4-27. Each pushpin represents an individual vehicle, almost all of them taxicabs.
Like Google Local searches, Google Ride Finder receives its annotations in their geodata format. To find the location of this feed, look in the JavaScript file http://labs.google.com/ridefinder/data?file=ride_js, referenced from the HTML source. The Update Vehicle Locations button calls refreshMarkers(), which then calls updateMarkers(). This function constructs the following URL:
	var j="/ridefinder/data?marker=1&lat="+f+"&lon="+g+"&z="+m+
	    "&src="+w+"&notes="+(new Date()).getTime();
Figure 4-27: Ride Finder in Chicago
In this bit of code, f and g are the lat/long center of the map, m is the zoom level, and w is hardcoded to 3. The notes argument is a timestamp, which seems to be appended to avoid hitting any cache. Constructing a URL with, for example, the center of Manhattan and scale 8, confirms that this is the feed for Ride Finder.
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 Google Maps Got Me Out of a Traffic Ticket
The democratization of research is demonstrated, and Google Maps serves the cause of justice by answering a basic, but disputed, factual question.
In January of this year, I was pulled over by a traffic officer for "disobeying a steady red," a.k.a. running a red light. I pleaded not guilty to the charge, and, nearly six months later, I went to court to find out the fate of my ticket violation. In the end, it was nearly down to my word against the officer's— but Google Maps saved the day!
There I was, on a bench waiting for my name to be called at the downtown Manhattan DMV hearings bureau. After hearing several testimonies from other drivers I knew this judge wasn't going to be sympathetic to my troubles. She heard driver after driver, but only one had a happy ending (from the driver's point of view).
So I was worried, because being found guilty would mean a $150 fine, plus $50 in penalties, and—worst of all—points on my license. I began to contemplate how it all happened since it had been so long. I jotted down some notes on a small piece of paper, and then came the moment of truth.
After my name was called, I gathered my belongings and made my way up to the stand where the ticketing officer joined me. The judge swore her in and asked for her testimony. The officer did just what I expected—after all, I had been listening to those prior testimonies—and began to describe the scene of the violation. In her story, I noticed one fatal flaw, which I wanted to exploit—but I had no proof whatsoever. The officer stated that the street I was on was a one-way westbound street, and that I was turning onto an avenue that was a two-way street separated by a concrete divider. The flaw was that I had actually been on a two-way street, not a one-way.
At last, the time came for my testimony, and I stated that I had been in midturn, when an oncoming vehicle came toward me very quickly, and I had decided not to make the turn until that SUV passed me. The Judge stopped and asked me how there could be an oncoming vehicle if the street was only one-way. I stated that it was actually a two-way street. The officer reiterated that it was a one-way. Who was the judge to believe? I was desperate for proof, so I did the obvious: I whipped out my notebook computer. I was very lucky to find an extremely bad connection via Wi-Fi. I pulled up Firefox and went to
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 5: Google Maps in Words and Pictures
The reason people love maps so much is that maps tell stories about places, and people love stories. Maps provide a narrative and a context for understanding the world around us. Even the most mundane maps tell a story; for example, a road or subway map's story is about how to get around quickly.
In this chapter, we're going to explore the narrative possibilities inherent in Google Maps. We'll see how Google Maps can be a reading aid, how satellite images don't always tell the full story, and how Google Maps can be mated with online photo services such as Flickr to establish a geographic context for the stories that our photographs tell. Finally, we'll look at the user-friendly end of the "geospatial web," where Google Maps can be used to produce and visualize feeds of information from other sources, to weave our story together into the many stories being told every day on the Internet.
If maps tell stories, what about the stories that tell maps?
"I lean against a USA Today paper box on Washington and Clark and think, 'Who the hell are you to make such a claim?'" That's the second sentence from the book Bike Messengers and the Cult of Human Power by Travis Hugh Culley. It is the story of Travis' work as a bicycle messenger in Chicago. Why did Travis pick that intersection? Did that just happen to be where he was, or does it have more meaning? Where is Washington and Clark?
Enter "Washington and Clark, Chicago, IL" in the location search box and we see in Figure 5-1 that the intersection is, well, in the middle of a lot of streets. That helps, maybe, a little. But I don't know Chicago, so all it means to me is a lot of streets.
Clicking on Satellite gives us the jackpot of Figure 5-2: the intersection is right smack in the middle of downtown.
Figure 5-1: A map of Chicago showing the action in Bike Messengers and the Cult of Human Power
Figure 5-2: The satellite view gives us the big (or at least elevated) picture
Different zoom levels give us, well, different pictures. Figure 5-2 shows an overview of the whole city, but when we zoom way in as in Figure 5-3,we see a 4-block by 3 1/2–block window of downtown Chicago. Looking at that, I can almost smell the bus fumes.
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 42–50: Introduction
The reason people love maps so much is that maps tell stories about places, and people love stories. Maps provide a narrative and a context for understanding the world around us. Even the most mundane maps tell a story; for example, a road or subway map's story is about how to get around quickly.
In this chapter, we're going to explore the narrative possibilities inherent in Google Maps. We'll see how Google Maps can be a reading aid, how satellite images don't always tell the full story, and how Google Maps can be mated with online photo services such as Flickr to establish a geographic context for the stories that our photographs tell. Finally, we'll look at the user-friendly end of the "geospatial web," where Google Maps can be used to produce and visualize feeds of information from other sources, to weave our story together into the many stories being told every day on the Internet.
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 More out of What You Read
If maps tell stories, what about the stories that tell maps?
"I lean against a USA Today paper box on Washington and Clark and think, 'Who the hell are you to make such a claim?'" That's the second sentence from the book Bike Messengers and the Cult of Human Power by Travis Hugh Culley. It is the story of Travis' work as a bicycle messenger in Chicago. Why did Travis pick that intersection? Did that just happen to be where he was, or does it have more meaning? Where is Washington and Clark?
Enter "Washington and Clark, Chicago, IL" in the location search box and we see in Figure 5-1 that the intersection is, well, in the middle of a lot of streets. That helps, maybe, a little. But I don't know Chicago, so all it means to me is a lot of streets.
Clicking on Satellite gives us the jackpot of Figure 5-2: the intersection is right smack in the middle of downtown.
Figure 5-1: A map of Chicago showing the action in Bike Messengers and the Cult of Human Power
Figure 5-2: The satellite view gives us the big (or at least elevated) picture
Different zoom levels give us, well, different pictures. Figure 5-2 shows an overview of the whole city, but when we zoom way in as in Figure 5-3,we see a 4-block by 3 1/2–block window of downtown Chicago. Looking at that, I can almost smell the bus fumes.
Caught in the rush of plot, too often I'll let the details slide. Hollywood and Vine? Washington and Clark? Who cares? I just want to see what happens next! But if that is all that matters, why should authors bother with place names? Why not simply write as if everything happened in the same grey protoplasmic sea? Context matters: the places where things happen shape what happens and what we think about what happens. Context feeds the mind.
Figure 5-3: The satellite view tells another story
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Don't Believe Everything You Read on a Map
Learn how the selection of imagery can be extremely subjective.
It is easy to assume that maps are somehow true and objective representations of a place. After all, most of our interactions with maps have to do with practical affairs such as navigating the complex layout of a city. The truth, however, is that maps both reflect and create reality. This is most clear in the choices of what is, and is not, put on a map.
For example, chamber of commerce maps typically show lots of green for parks and greenbelts, but somehow neglect to point out the less desirable aspects of a community. Okay, you might say, the maps are subjective, but I can count on the aerial imagery, right? It is just a record of how things were. Alas, even there we have issues. There is a huge possibility for bias in the choices of images that will be displayed.
Figure 5-4 shows part of the Black Rock desert in Nevada, near the town of Gerlach. For most of the year this is an empty expanse where you can either hear yourself think or hear the people cruising about trying to set land-speed records in the armed-and-inebriated SUV-driving category. However, for a week, plus time before and after for set up and clean up, this is Black Rock City, home to the Burning Man festival. This particular image was taken during the setup period for the 2003 event.
Figure 5-4: A bit of desert in Nevada, late summer
How did that happen to become the canonical Google representation of an area around 40.7549 N, 119.23608 W? I suspect that it wasn't pure chance! Was it an accident that the aerial photo in Figure 5-5 centered around 37. 713532 N, 122.386075 W shows the San Francisco 49ers' football stadium near Candlestick Point State Park in the middle of a game?
On the other hand, the aerial photo in Figure 5-6 centered on 37.751367 N, -122.201239 W shows the nearby home of the Oakland Raiders, another football team, to be empty and configured for a baseball game??
The simplest explanation is that maps tell stories, and so these particular mapmakers configured reality through selection of imagery in order to tell a more entertaining story. After all, according to Muriel Rukeyser, "the universe is made up of stories, not atoms."
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
You Got Your A9 Local in My Google Maps!
Use Greasemonkey to inject A9's Local Images into Google's much nicer map interface.
A9.com, Amazon's search company, has special trucks equipped with digital cameras and GPS units that run around selected cities. The trucks take street-level pictures of just about everything and then index that with the GPS and a geocoding application to add photographs to business listings. A9.com "brings Yellow Pages to life." Figure 5-13 shows the A9 Block View of the City Lights bookstore in San Francisco.
A9.com is pretty neat, but the mapping interface is a bit weak. If you have the Greasemonkey extension installed in the Firefox browser, you can install A9+Gmaps, a Greasemonkey user script that will load A9 images on top of your Google Maps.
Installing Greasemonkey in Firefox is covered in detail in "Add Google Maps to Any Web Site" [Hack #27] and "Track Your UPS Packages" [Hack #25] .
Figure 5-13: City Lights bookstore, according to A9.com
Once Greasemonkey has been installed in Firefox, you can get A9+Gmaps from http://www.kokogiak.com/webtools/greasemonkey/a9imagesingooglemaps.html. From that page, right-click on the link to a9gmap.user.js and select Install User Script. An installation window will pop up, as depicted in Figure 5-14.
Click on OK, and with a bit of luck you'll get a status window that says "Success! Refresh page to see changes." Now, when you search for a business on the Google Maps web site in an area covered by A9 Local, you'll be able to click on the icon and, a few seconds later, an A9 thumbnail will appear in your info window.
The A9+Gmaps Greasemonkey script is executed whenever a user is on a page in the maps.google.com domain. When the user clicks on an icon in the map, the script finds the newly opened info balloon and parses the HTML inside it to find the business name and address, if present. The script then sends that data out to A9.com, behind the scenes. When A9.com responds, the script parses A9's HTML to discover an image (if one exists), and gets the location and URL of the A9.com image and page. Finally, the script inserts a thumbnail image of that location into the Google Maps info window.
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 Pictures with Your Community
Use Flickrcity to set up a collaborative photo map.
Putting geolocated photos on a map is something geo-hackers have worked on for a long time. Now, using Flickr, Google Maps, and a little piece of glue called Flickrcity (http://anti-mega.com/flickrcity/), anyone can do this easily.
I started work on Flickrcity because I wanted to create a restaurant review site for Helsinki that anyone could contribute to. Flickr was the natural place to store photos and information; sites such as Geobloggers (http://www.geobloggers.com/) were using Flickr as a data source and had already created a standard for geotagging photos.
Flickrcity automatically filters on a tag of the name of the city and the tag geotagged. Using additional tags, or specifying a particular user, you can use Flickrcity for a variety of purposes.
To see all geotagged photos in a city, you can just go to the URL of the Flickrcity installation—e.g., for Helsinki, http://anti-mega.com/flickrcity/helsinki.city, as shown in Figure 5-15.
Figure 5-15: Photos geotagged in Helsinki
If you wanted to set up a collaborative restaurant review site for Helsinki, you would need to tag photos in Flickr with, say, "helsinki," "food," "geotagged," and the two location geotags [Hack #46] . Then you would construct a URL that would return these images with this tag query, such as http://anti-mega.com/flickrcity/helsinki.city?tags=food. Figure 5-16 shows what this looks like.
If you just wanted to see all of my Helsinki photos, you would use a user query such as http://anti-mega.com/flickrcity/helsinki.city?user=chrisdodo, as Figure 5-17 demonstrates.
Of course, you can combine the two, to show just my food photos, as in http://anti-mega.com/flickrcity/helsinki.city?tags=food&user=chrisdodo.
If you're using the map for yourself, use a different tag for each project you want to create. If you want to set up a collaborative map, pick a tag name that isn't being used in Flickr and tell all your photographers to add that tag. Of course, others may see it and start using the tag too—Flickrcity gets even better with more geotagged photos.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Browse Photography by Shooting Location
What a lovely photograph! Where was it taken?
Since the rise of digital photography, more people have been snapping more photos than ever. Web sites such as Flickr have sprung up to help people manage and publish their photos, and Flickr itself has gone one step further and allows its users to "tag" their photographs with keywords that indicate what's being depicted. These tags can help you figure out who and what is being depicted, but wouldn't it be nice sometimes—particularly in the case of those lovely landscape photos—to know where they were taken?
Fortunately, Flickr provides an API that allows you to query data from its system, and we can use this to find images that have been geotagged. Geotagged photos on Flickr have three special tags associated with them. First, they're tagged as geotagged, which allows us to find them using the Flickr API. Second, they have the tags geo:lat=…and geo:long=…associated with them, which gives us their geographic coordinates. Figure 5-18 shows one sort of map that can be made by mashing up the Flicker API and the Google Maps API.
In order to make use of the Flickr API, you need to sign up to Flickr, and then get yourself an API key from http://www.flickr.com/services/api/. Once you have a key, you can query Flickr using the flickr.photos.search call from their REST API, with a URL like:
	http://www.flickr.com/services/rest/?method=flickr.photos.search&api_ 
	key=[your API key]&tag_mode=all&tags=geotagged&per_page=20
This returns an XML document matching the latest photos tagged as geotagged. The XML looks something like the following:
	<?xml version="1.0" encoding="utf-8" ?>
	<rsp stat="ok">
	       <photos page="1" pages="8553" perpage="5" total="42761">
	       <photo id="30221122" owner="47836075@N00" secret="11f6695a02"
	                 server="21" 
	           title="From Camera Server(SlabbersCam)0000/00/06,15:00:07" 
	           ispublic="1" isfriend="0" isfamily="0" />
	       <photo id="30218138" owner="78211664@N00" secret="5a36fff7b3" 
	                 server="21" title="P8010502" ispublic="1" isfriend="1" 
	                 isfamily="1" />
	       <photo id="30218130" owner="78211664@N00" secret="8bda841d8b" 
	                 server="23" 
	           title="P8010498" ispublic="1" isfriend="1" isfamily="1" />
	       
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Geotag Your Own Photos on Flickr
Maps and pictures go together like a horse and buggy.
Ever since Flickr started cataloguing people's digital photography, many have been clamouring to be able to geolocate photos. The idea of geotags was proposed by Dan Catt. As described in "Browse Photography by Shooting Location" [Hack #46] , Dan created a service called Geobloggers (http://www.geobloggers.com) to aggregate the geotagged photos.
One of Flickr's key features is that it allows you to add tags to your photos. A tag can be a word or group of words, such as "vacation" or "my kids." There are three tags you need to add to photos to be able to geolocate them: geo: lat=xx.xxxx, geo.lon=yy.yyyy, and geotagged.
The latitude and longitude are expressed in decimal degrees. Latitudes south of the equator and longitudes west of Greenwich are negative. As different latitudes and longitudes appear to be different tags to Flickr, the geotagged tag is necessary to let you search for geotagged photos. There are two ways to geotag photos: manually and using Google Maps.
If you have a GPS, use it to record the latitude and longitude as you take photos by taking a photo of the GPS. You can set the GPS to display in decimal degrees (which may be represented as hddd.ddddd° in the GPS settings), however, GPSes often display in degrees and minutes, as shown in Figure 5-20, or degrees, minutes, and seconds.
Figure 5-20: Take a photo of the GPS to make geotagging easy
If you have GPS coordinates in degrees, minutes, and seconds, try the FCC's converter at http://www.fcc.gov/mb/audio/bickel/DDDMMSS-decimal.html.
In Flickr, add the three tags to each photo, which is represented by that latitude and longitude. Taking the location in the photo as an example, the tags I would add to the photo are:
	geo:lat=71.171067
	geo:lon=25.783050
	geotagged
There is, thankfully, an easier way. We can use Google Maps and a nifty Greasemonkey script to do all the heavy lifting for us.
The hard bit is setting up. You need to install Firefox (http://www.mozilla.org/products/firefox/
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Tell Your Community's Story
Give a guided tour of your community with photos and a Google Map.
We've all been there before; huddled around a computer, looking at photo after photo of a friend or family member standing in front of one tourist attraction after another. I don't know about you, but after the third picture I start to fade fast. It's not that the pictures are necessarily boring (although they very well might be); they're just so repetitive.
The laws of physics require that a photo be a representation of a physical place, but we so rarely display photos within any context of physical location. Google maps provides just such a context, and the effect of placing photos on a map at the location they were taken adds an extra dimension of information to the photo. I'm not suggesting that your slideshow of Hawaii with eight photos of you on the shores of a beautiful beach will become the most enthralling presentation ever, but you might hold people's attention for six photos rather than three.
Community Walk (http://www.communitywalk.com/) attempts to facilitate the process of placing photos on a map showing where they were taken. The intent of it was, surprisingly enough, not to simply alleviate the boredom of vacation slideshows, but rather to allow people to share their communities. I roughly define a community as a group of things that share some commonality in the mind of some person or group of people. Although a community does not necessarily have to exist in a physical area, it does have to involve something that exists in a physical location, even if that is just the people that are involved in the community.
Many communities may exist in the same physical area as well. It all depends on the perspective of the people involved. A baseball fan may see SBC Park in San Francisco as one of the many ballparks in the United States, as shown in Figure 5-26.
The manager of a hotel may see the ballpark as a highlight of the area around the hotel, as in Figure 5-27.
With Community Walk, I wanted to give people a way to share these different perspectives, providing different ways to organize and display the various things in a community on a map. I also wanted to allow the creator of the map to configure the map to behave exactly as desired. The hotel manager may not want anyone else to be able to edit the map of the hotel or write comments on the various locations on the map, while the ballpark aficionado may want to allow certain people to edit the map and everyone to add comments about the various ballparks and baseball teams that play in those parks. Community Walk allows for all this and then some.
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 Geocoded RSS from Any Google Map
Don't tell anyone, but the Semantic Web really is cool.
One thing that bugs me about Google Maps is that, since the API is entirely JavaScript, the annotation layer in a hack is only available visually and is not machine parseable. It's understandable that Google didn't push any particular geodata file format, as these will emerge, but it's frustrating that right now so much cool data is being created as lone silos, in an inaccessible and un-remixable way.
Yet the data is there, in the JavaScript and Document Object Model objects created by the Google Maps API. It should be possible to muck around in there and rescue that data from its lonely and isolated existence. This hack describes a Firefox JavaScript Bookmarklet that pulls point annotation information from many Google Map hacks and produces geocoded RSS.
The first step is to find the GMap object in memory, which is the key to the Google Maps object structure. Every page that shows a Google Map (under the official API) must have a line that looks like this:
	var map = new GMap(document.getElementById("map"));
The bookmarklet assumes the GMap object is a global variable. If the page creates the GMap object within a function, the bookmark will fail. User-created global variables and methods can be accessed by iterating through the global object this. Without a JavaScript function to query an object for its user created class, the bookmarklet calls getCenterLatLng( ) on each global object within a try/catch block. If this call does not generate an error, the GMap object has been found and things can move forward. The other assumption is that overlays are GMarker objects that respond to click events by calling openInfoWindowHtml(). This is probably the most common way of constructing a Google Map.
Since there is no API method to list overlays, a JavaScript Data Dumper, such as the one at http://www.mattkruse.com/JavaScript/datadumper/, can be very useful to investigate the structure of the GMap object and find the overlays, without following through the API's obfuscated code. We can start by creating a basic Google Map with overlays and info windows, according to the documentation. Next, we load in
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Geoblog with Google Maps in Thingster
Share your favorite places with friends.
In this hack, I discuss our Thingster Geoblogging service and some of the details of how I integrated Google Maps. We provide Thingster free of charge at http://www.thingster.org/, and it is open source and open data licensed as well. You're welcome to log in, create an account, and play with it; you're also welcome to run your own copy or just take any ideas you like and build your own equivalent.
My own interest in place-tagging came from a very simple desire: I wanted to be able to share information about my favorite places with my friends. The fact that there are not 10,000 companies already doing this has always completely mystified me. It seemed like a perfectly logical business plan if you were so minded—certainly better than, say, "pets.com."
It is pretty obvious that the blogging paradigm is the right way to hang Post-It notes in space. People already use blogs in almost exactly this way: you own your own blog, you publish in a formal publishing framework, and blogs export this wonderful RSS format that is machine-readable. Blogs have already been extended to blog pictures, songs, and even video: blogging by location is the next logical step.
The challenge in blogging about places is that our blogging tools or content management systems need to support some kind of satisfying, fast, and compelling map interface. These tools need to be as easy to use as ordinary blogging tools. A clever novice should be able to walk up to a mapping service, create an account, and post her first geotagged post in under a minute.
In 2004, Ben Russell and I first conceived Thingster as an "anything tool," where one could blog about any kind of thing. Maps were the first clear interest and my good friends Tom Longson and Brad Degraf quickly jumped on board to help play with the idea. We thought that if community driven maps existed, then we could start to share information about our communities more intelligently, and that this might even change the way we engage and interact as citizens. This is the sort of big if
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 6: API Tips and Tricks
The official Google Maps API makes a lot of things easy. Here are some hacks that push the API in new directions and extend the API with external libraries. Tricks such as filling your whole 21-inch flat panel display with a map, customizing your info windows with an embedded map the way the driving directions work, and integrating Flash with your maps.
You can even add custom labels and photographs on top of your Google Maps. Perhaps this technique reaches the height of elegance (absurdity?) when used to compare the size of Burning Man with New York's Central Park.
The chapter ends with several tricks to allow you to use one developer's key for multiple domains and directories. Do you really want to manage multiple keys because you have the domain http://mydomain.com and you serve the same pages from it and http://www.mydomain.com? I didn't think so!
Map too big? Map too small? Flex those pixels into shape!
Imagine you're the proud new owner of a big, shiny 21-inch flat-panel display, and you surf to your favorite Google Maps web site—only to find it still confines you to a tiny little 3-inch-square map. It's an embarrassment, to say the least. Likewise, think about those poor fellows with small monitors who are scrolling until their fingers fall off to get around your gigantic 1600 x 1200–pixel map. Such sites ought to come with warning labels about claustrophobia.
A good Google Map stretches itself to fit comfortably on your screen. In this hack we'll investigate a simple two-step approach to make your map always take up the whole window, then build on the technique to include a fixed right-side panel, similar to the maps.google.com web site. We'll also point out some tricks to help you avoid common pitfalls that unsuspecting web developers stumble into when trying to make auto-sizing maps.
The first step is to include the following style declaration in the head section of your page. If your map div is named something other than map, you'll need to replace #map with the appropriate name (e.g., #mymap).
	<style type="text/css">
	       html, body, #map {
	           width: 100%;
	           height: 100%;
	       }
	       html {
	           overflow: hidden;
	       }
	       body {
	           margin: 0px 0px 0px 0px;
	           padding: 0px 0px 0px 0px;
	       }
	</style>
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 51–61: Introduction
The official Google Maps API makes a lot of things easy. Here are some hacks that push the API in new directions and extend the API with external libraries. Tricks such as filling your whole 21-inch flat panel display with a map, customizing your info windows with an embedded map the way the driving directions work, and integrating Flash with your maps.
You can even add custom labels and photographs on top of your Google Maps. Perhaps this technique reaches the height of elegance (absurdity?) when used to compare the size of Burning Man with New York's Central Park.
The chapter ends with several tricks to allow you to use one developer's key for multiple domains and directories. Do you really want to manage multiple keys because you have the domain http://mydomain.com and you serve the same pages from it and http://www.mydomain.com? I didn't think so!
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Make a Fullscreen Map the Right Way
Map too big? Map too small? Flex those pixels into shape!
Imagine you're the proud new owner of a big, shiny 21-inch flat-panel display, and you surf to your favorite Google Maps web site—only to find it still confines you to a tiny little 3-inch-square map. It's an embarrassment, to say the least. Likewise, think about those poor fellows with small monitors who are scrolling until their fingers fall off to get around your gigantic 1600 x 1200–pixel map. Such sites ought to come with warning labels about claustrophobia.
A good Google Map stretches itself to fit comfortably on your screen. In this hack we'll investigate a simple two-step approach to make your map always take up the whole window, then build on the technique to include a fixed right-side panel, similar to the maps.google.com web site. We'll also point out some tricks to help you avoid common pitfalls that unsuspecting web developers stumble into when trying to make auto-sizing maps.
The first step is to include the following style declaration in the head section of your page. If your map div is named something other than map, you'll need to replace #map with the appropriate name (e.g., #mymap).
	<style type="text/css">
	       html, body, #map {
	           width: 100%;
	           height: 100%;
	       }
	       html {
	           overflow: hidden;
	       }
	       body {
	           margin: 0px 0px 0px 0px;
	           padding: 0px 0px 0px 0px;
	       }
	</style>
The width and height declarations cause the map container to fill the entire document body, and the body to take up all the available window space. Make sure you don't have any inline width or height attributes on your map element that could override these. The overflow:hidden line hides any scrollbars the browser would otherwise display, and the margin and padding lines get rid of the white border that is shown by default around a document. This leaves us with a map container that stretches to fit all the available window space in the browser (minus that reserved for the toolbars, status bar, etc.).
The Google map automatically takes up this whole container when you instantiate it, and most web developers stop here, thinking all is well. However, somewhat less obvious is the fact that the map doesn't detect when its container has been resized—at least, not as of version 1 of the API. Resizing a map that isn't aware when its container size changes can produce some misleading effects, which you can see by going to
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Put a Map and HTML into Your Info Windows
Add more context to your info windows by including a map and HTML.
There are times you want to include both a map and some text in the same info window. With a little hackery you can get the sort of effect demoed at http://mappinghacks.com/projects/gmaps/map_in_box.html and shown in Figure 6-4.
Figure 6-4: A map and text in the same info window
Within the Google Maps API there is an info window class that enables you to click on a point or overlay and get additional information about whatever it was that you clicked on. According to the API documentation, there are really only two types of methods that create info windows. The first type is those that take some kind of HTML in one of their arguments, namely openInfoWindow(), openInfoWindowHtml( ), and openInfoWindowXslt( ). The second type is really just a single method that takes no HTML as input and produces a blow-up map of some point inside of the info window, but nothing else. This method is showMapBlowup().
There are also times when we need both a map and text in the same window. However, when we look at the full prototype for the showMapBlowup() method, namely showMapBlowup(point, zoomLevel?, mapType?, pixelOffset?, onOpenFn?, onCloseFn?), we see there is no way to insert text into a map blowup. How do we get a map and text into an info window?
When we look at the openInfoWindowHtml( ), we see that it has the prototype openInfoWindowHtml(marker, htmlStr, pixelOffset?, onOpenFn?, onCloseFn?), where htmlStr is any string of HTML. Well, since we are using a div element to create the main map, why not try putting a div element into the htmlStr? As it turns out, that works almost wonderfully:
	GEvent.addListener(testmarker, "click", function ( ) {
	 var text = '<p style="text-align: left">';
	 text += '<div id="minimap" style="width: 200px; height: 200px"></div>';
	 text += 'Here is some text.<br>';
	 text += 'This is a link to <a href=

	              "http://maps.google.com/">Google Maps</a>';
	 testmarker.openInfoWindowHtml(text);
	 var minimap = new GMap(document.getElementById(minimap));
	 minimap.centerAndZoom(pt,1);
	 minimap.addControl(new GSmallMapControl( ));
	});
	map.addOverlay(testmarker);
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 Flash Applets to Your Google Maps
Spice up your Google Map info windows with Macromedia Flash animation, and even Java applets.
Integrating Macromedia Flash with a Google Map is a snazzy way to enhance the multimedia experience of your web page. Although the examples given here are toys, no doubt the intrepid reader can find Useful Uses for this sort of integration in the real world.
As a first step, we'll embed a small Flash animation I've created called FlashBit.swf into the pop-up window of a marker. The animation is just some text with a blue ball that bounces across it when clicked, as seen in Figure 6-5.
We're going to use the openInfoWindowHtml( ) method of the GMarker class to add the required HTML to our document. The string we'll be passing is stored in a variable called flashHtml.
	flashHtml = '<object classid="clsid:d27cdb6e-ae6d-'
	    + '11cf-96b8-444553540000" '
	    + 'codebase="http://fpdownload.macromedia.com/pub/'
	    + 'shockwave/cabs/flash/swflash.cab#version=7,0,0,0" '
	    + 'width="128" height="53" id="FlashBit" align="middle">'
	    + '<param name="allowScriptAccess" value="sameDomain" />'
	    + '<param name="movie" value="FlashBit.swf" />'
	    + '<param name="quality" value="high" />'
	    + '<param name="bgcolor" value="#ffffff" />'
	    + '<param name="wmode" value="transparent" />'
	    + '<embed src="FlashBit.swf" quality="high" '
	    +  'bgcolor="#ffffff" width="128" height="53" '
	    +  'name="FlashBit" align="middle" '
	    +  'allowScriptAccess="sameDomain" '
	    +  'type="application/x-shockwave-flash" '
	    +  'wmode="transparent" '
	    +  'pluginspage="http://www.macromedia.com/go'
	    +  '/getflashplayer" />'
	    +  '</object></center>';
Figure 6-5: Flash animation in a Google Maps info window
Although the code above may look a little convoluted, it's really nothing more than a typical Flash object declaration. The object tag is used by Internet Explorer on Windows platforms, while Netscape and Internet Explorer for the Mac both use the embed tag instead. More information on why you need both tags can be found in Macromedia's knowledge base 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!
Add a Nicer Info Window to Your Map with TLabel
Callouts, info windows—anything that can fit on a web page—can fit on a map.
The early Google Maps hacks share a similar affliction: they suffer from red pushpin syndrome. Sometimes the pushpins are green. You can create custom icons, but they are a bit of a challenge, and then you just get a different little symbol.
What you (might) want is the ability to customize the map with unique info windows, images, callouts, and anything else that strikes your fancy. Tom Mangan created the TLabel extension to allow you to embed any DOM object (anything that can appear on a web page) on a Google Map. Figure 6-8 shows Tom's canonical example from the TLabel page at http://gmaps.tommangan.us/tlabel.html, with a Google satellite image of two U.S.
Air Force SR-71 Blackbirds and a U-2 spy plane at the Blackbird Air Park, in Palmdale, CA. (For the curious, this is at 34.602975 N, 118.085926 W.)
Figure 6-8: SR-71s at the Blackbird Air Park, with TLabel annotations
Callouts identify each plane. The numbers are links to sites that have more information on each plane. There is also a thumbnail image that was taken from ground level. The image has a tool tip that reads "Click for larger." Surprisingly, clicking on that link leads to a larger image of that thumbnail.
The TLabel page is at http://gmaps.tommangan.us/tlabel.html. There is a link to a JavaScript file, currently http://gmaps.tommangan.us/tlabel.19.js, but check for the current version. Copy that file onto your own server and include it after you include the Google Maps API.
	<script src="http://maps.google.com/maps?file=api&v=1&key
	      =AOJVHiMoLlyAv…x3sA" type="text/javascript"></script>
	
	<script src="tlabel.10.js" type="text/javascript"></script>
Now, create some objects! You control the TLabel object by creating a new object and then setting the properties. There is a demo of some TLabel tricks at http://mappinghacks.com/projects/gmaps/brc_tlabel.html. Here is code to create a label, as shown in Figure 6-9:
	var label = new TLabel();
	label.id = 'mail_box';
	label.anchorLatLng = new GPoint (-119.226396, 40.768080);
	label.anchorPoint = 'bottomLeft';
	label.content = 'Mail Box';
	label.percentOpacity = 85;
	map.addTLabel(label);
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Put Photographs on Your Google Maps
Treat photographs as map layers and add them to your Google maps.
While figuring out how to lay my own images into the Google Maps interface, I ended up with some pretty useful JavaScript, so I bundled it up as a tightly integrated extension to the official API. The result is TPhoto. TPhoto allows you to embed alternate aerial photographs inside your Google Maps. The added photos pan and zoom along with the main map view, without interfering with any clicks on the map. Figure 6-10 shows an example of an aerial photo of Groom Lake from 1959 overlaid over the Google Satellite imagery.
Figure 6-10: Groom Lake, 1959
Groom Lake. Dreamland Resort. Watertown. The Ranch. For such a secretive place, people certainly know it by a lot of names! The image in Figure 6-10 comes from my Area 51 page at http://gmaps.tommangan.us/groom_lake.html. Figure 6-11 shows a 1968 image over the Google Satellite imagery.
You can add the ability to overlay photos onto your own Google Maps by installing the TPhoto extension.
Download the TPhoto library from http://gmaps.tommangan.us/tphoto.html/. The current version is tphoto.16.js, available at http://gmaps.tommangan.us/tphoto.16.js. Place it on your server and include it after you include the Google Maps API in your JavaScript. You could include it directly from the tommangan.us server, but it is on very rare occasions not available, so I recommend you download the file to your own server and link it as shown here:
	<script src="http://maps.google.com/maps?file=api&v=1&key=ApAUl_iS-dEaDI.RA"
	      type="text/javascript"></script>
	<script src="tphoto.16.js" type="text/javascript"></script>
There are two ways to use TPhoto. In the first method, you supply the lat/long of the top left and bottom right corners of your image. In the second method, you supply a single lat/long anchor point, the base zoom level, and the dimensions of your image. The first method looks like:
	var groom1959 = new TPhoto();
	groom1959.id = 'groom1959';
	groom1959.src = 'images/groom1959.jpg';
	photo.percentOpacity = 50;
	groom1959.anchorTopLeft = new GPoint(-115.823107,37.248368);
	groom1959.anchorBottomRight = new GPoint(-115.801649,37.230123);

	map.addTPhoto(photo);
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Pin Your Own Maps to Google Maps with TPhoto
Georeference your own maps and then pin them anywhere.
The first time I visited New York City from the Bay Area, I was excited to see everything, all at once. I figured that Manhatten is small, about 10 1/2 miles from tip to tip, and the boroughs are just a bit larger. How long could it take to go 10 miles?
A temporary New Yorker friend told me, "You can think of Manhattan as being the whole Bay Area. Sure you can drive from Palo Alto to San Francisco, across to Oakland and down the East Bay to San Jose, but would you? Manhattan is physically smaller, but in terms of travel times it is similar."
We can use TPhoto [Hack #55] to take an image of one place and center it in another. At http://www.mappinghacks.com/projects/gmaps/brc_ref.html you see the Google aerial photo of the site of the Burning Man festival in the Black Rock desert of Nevada. If you click "show plan," you'll get the 2005 Burning Man city plan overlaid on the Google Map as shown in Figure 6-14.
Figure 6-13: Blackbirds at 100% opacity
But you don't have to overlay the city plan on the Google Map in the proper place! You can scroll the map to another area and then click on a point to overlay the city map on that point. Figure 6-15 shows a hypothetical Burning Apple festival centered on 79th Street in the middle of Central Park.
It is interesting that Manhattan is oriented nearly the same way as the Playa, from southwest to northeast, and the Festival covers about two-thirds of the width of Manhattan. The Metropolitan Museum of Art ends up more or less by the Large Scale Sound installations.
The distance from Center Camp to the perimeter fence is about 27 city blocks—from 72nd Street to 99th Street. And moving out a few zoom levels leaves us in awe at how tremendously big and dense an experience it is to be in New York.
Taking it home, way home to Sebastopol, and centering on O'Reilly, gives us the results in Figure 6-16.
This was produced with the single-point method of TPhoto [Hack #55] . This makes TPhoto work as a simple georeferencing tool. Georeferencing is the act of mapping the pixel space of an image to a coordinate system that is pegged to the earth's surface.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Do a Local Zoom with GxMagnifier
Context is key: GxMagnifier lets you choose the appropriate context.
The zoom feature on Google Maps is nice, except when you want to see a zoomed out view so that you have some context and yet still see detail. The normal cartographic answer to that conundrum would be that you are out of luck. Lucky for us, this is no ordinary cartographic environment!
GxMagnifier is a free add-in control for Google Maps that creates a moveable, magnified window on top of your map. Figure 6-17 shows GxMagnifier in action.
Figure 6-17: GxMagnifier's "Hello World"
Does this look like an ordinary Google Map to you? Click the magnifier icon in the top-left corner of the map. Now, wherever you go on the map, you get a magnified view. This feature can be used with a mere two lines of code. Like a lot of JavaScript libraries, you first load it:
	<script src="GxMagnifier.1.js" type="text/javascript"></script>
Then, add the control in your code:
	map.addControl(new GxMagnifierControl());
Note that we're passing a custom control object to the standard map.addControl API call. This is all you need to do to get the basic magnifier control. This is only the most basic example of what GxMagnifier can do! The full documentation, with complete reference to the API can be found here: http://www.googlemappers.com/libraries/gxmagnifier/docs/default.htm.
In our simple example we instantiated the GxMagnifierControl object within our map.addControl() call:
	map.addControl(new GxMagnifierControl());
This is a dead simple approach, but it doesn't allow us to control the GxMagnifierControl later on. GxMagnifier can do more for us! The next examples will start with this basic framework, with the crucial lines highlighted. Of course, you'll need to use your own developer's key.
	<!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>
	          <title>GxMagnifier Example Framework</title>

	          <script src="http://maps.google.com/
	maps?file=api&v=1&key=ilovemykidsmandms" type="text/javascript"></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!
Find the Right Zoom Level
You've got some points to show on a map. How do you pick the right zoom level to show them all at once?
The Google Maps API is powerful but, as tends to be the case for such toolkits, has some omissions and inconveniences. For example, in many real-world mapping problems, it's common to have a set of points or lines that we wish to display on a map. Typically, we choose the outer four corners, or extents, of the map to match the bounding box of the data, which is given by the minimum and maximum x and y coordinates in our data set. By selecting the map extents to match the bounding box of the data, we can guarantee that everything we want to show should be visible in the map display.
The bounding box of a data set is usually very easy to calculate. One way to do so is to simply iterate through the data set, looking for the largest and smallest coordinates in both dimensions. The problem is that the Google Maps API doesn't give us any way to set the map extents based on a bounding box. Instead, the API exports a centerAndZoom( ) method that accepts a center point of the map, expressed as a latitude and longitude pair, and a zoom level. Google documents the zoom level as an integer, and the examples in their documentation all use 4 as the zoom level, but no definition of the zoom levels themselves is given. Experimentation shows that they correspond with the ticks on the zoom level control.
Our question is then very simple: given a bounding box, how does one determine an appropriate center and zoom level, so that our data is guaranteed to appear on the screen, regardless of screen geometry?
One approach is to look at the current map geometry and see if the screen will hold the bounding box and keep zooming in or out as needed. The zoom levels are approximately powers of two, so it's practical to use a sort of brute-force method, and just multiply or divide the current level by two, and see if it still fits. The following JavaScript does just that:
	function computeZoom(minX, minY, maxX, maxY) {
	  var zl;
	  var bounds = map.getBoundsLatLng();
	  var cz = map.getZoomLevel();
	  var mapWidth = Math.abs(bounds.maxX - bounds.minX);
	  var mapHeight = Math.abs(bounds.maxY - bounds.minY);
	  var myWidth = Math.abs(maxX - minX);
	  var myHeight = Math.abs(maxY – minY);
	  var changeZoom = myWidth > mapWidth ? 1 : -1;
	  // Just rip through until we find the lowest that will hold our span.
	  // For certain geometries (around hemisphere boundaries), this won't work
	for(zl=map.getZoomLeve( );zl> 2&&zl<17; zl += changeZoom) {
	   width = width * Math.pow(2, changeZoom);
	   height = height * Math.pow(2, changeZoom);
	   if ((width < lon) || (height < lat))
	     return zl - 1;
	  }
	  return zl;
	}
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Show Lots of Stuff—Quickly
Lots of Google Maps overlays means lots of time spent waiting for them to draw on the map—unless you're smart.
When dealing with nontrivial numbers of overlays to draw on a Google Map—as in more than a hundred or so markers or vertices in a polyline—the drawing time required for a GMap object becomes really noticable. The inclination is to want to show markers as quickly as possible, so that the user gets immediate feedback on what's going on, but it's been discovered that if you buffer the objects and then manually trigger the redraw, it is much faster.
We can accomplish this buffering by adding a custom method of our own to the Google Maps API, which we'll call addOverlays( ). By assigning it to the GMap class prototype, it becomes available on any GMap objects we create. The code looks like this:
	// This is a bit of a trick for the 1.0 API. The 'addoverlay' method
	// is agonizingly slow, so we buffer up the markers in the 'overlays'
	// array and then deliver them to GMAP in one shot.

	GMap.prototype.addOverlays=function(a) {
	        var b=this;
	        for (i=0;i<a.length;i++) {
	                try {
	                           this.overlays.push(a[i]);
	                           a[i].initialize(this);
	                           a[i].redraw(true);
	                } catch(ex) {
	                        alert('err: ' + i + ', ' + ex.toString());
	                }
	        }
	        this.reOrderOverlays();
	}
The addOverlays() method can be used directly in your code or included via a script element in your HTML, after you include the Google Maps library.
Using this technique is really easy—instead of calling map.addOverlay( ) for each marker or polyline we create, we'll push each overlay onto an array, and then pass the array to map.addOverlays( ). Here's a fragment of a simple GPX reader that displays waypoint data using this idea:
	var wpts = GPX.documentElement.getElementsByTagName("wpt");
	var markers = [];
	for (var k = 0; k < wpts.length; k++) {
	      var point = new GPoint(trkPts[k].getAttribute("lon"),
	                             trkPts[k].getAttribute("lat")));
	      var marker = new Gmarker(point);
	      // … we could do things with the marker here,
	      // like set a custom icon or configure an info window …
	      
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Make Things Happen When the Map Moves
You can make your maps more interactive by responding to user-initiated events.
Balancing what to show and what not to show on a Google Map can be tricky. On one hand, for performanc reasons, you want to restrict the overlays displayed on the map to just the ones that would appear within the current view. On the other, if the user should pan or zoom the map, you might want the map's contents to change in response. Fortunately, the Google Maps API offers a way to make this happen automatically.
Poor Clio's Side-by-Side Google Maps at http://jamesedmunds.com/poorclio/googlemap11.cfm offers a terrific example of how Google Maps hacks can respond to user actions. The site, built by James Edmunds, shows two Google Maps of the same location side by side. On the left, the regular map mode is shown, while the map on the right shows the same map in satellite mode. Figure 6-20 shows the side-by-side view of the area around 30th Street Station in Philadelphia, with the rail yards extending away to the north.
Figure 6-20: Two views of Philadelphia's 30th Street Station, side by side
What's novel about this site is that if you drag the map on the left with your mouse, double-click to recenter it, or zoom in or out, the satellite view on the right recenters and zooms to match. Until Google introduced hybrid mode maps, this was effectively one of the only ways to compare the satellite and map views. The secret to how it works lies in the Google Maps Event API.
If you've written or looked at JavaScript code that uses the Google Maps API to cause info windows to pop up when the user clicks on a marker, then you've probably seen a method call that looks like this:
	GEvent.addListener(marker, "click", function( ) {
	    marker.openInfoWindowHtml(html);
	});
This method uses the GEvent class to register a click event on a marker object. When the marker is clicked, the anonymous function gets called, and the info window is opened. As it happens, the Google Maps API offers several other events for tracking and responding to user interactions.
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 the Right Developer's Key Automatically
What to do when your web site lives at two domains that resolve to the same server.
Adding a Google Map to our web page [Hack #10] solved all our problems. Right? Not quite. The map works perfectly when we use http://geocoder.us, but the DNS for the Geocoder site, like that of many sites, is configured to treat http://www.geocoder.us/ as a synonym for http://geocoder.us/. The two domains resolve to the same server, which means that the same page will be served up to people asking for either domain. This works fine, until you put the Google Maps API key into the mix.
When you have the same Google Maps hack on two different URLs, even though they point to the same place, you get the message "The Google Maps API key used on this web site was registered for a different web site. You can generate a new key for this web site at http://www.google.com/apis/maps/." One can be forgiven the odd chuckle at the irony of http://maps.google.com/apis/maps/, as shown in Figure 6-21.
Figure 6-21: Getting the developer key right is a tricky thing
How does Google know what server and directory your request is coming from?
For Google Maps to work you need to include the Google Maps JavaScript library into your page as shown in this example:
	<script
	       src="http://maps.google.com/maps?file=api&v=1&key=yourkeyhere"

	       type="text/javascript">
	</script>
A user will load your page by fetching it from your server. His web browser will then look through that page and identify images, scripts, plug-ins, and anything else that was not in the page and so needs to be loaded.
When the browser sees the script element, it attempts to load the script specified in the URL listed in the src attribute. When a browser asks for information from a web server, it also sends information, including the name of the server and the page that referred the user to get the script. Google Maps is probably using the HTTP referer that is automatically sent to the server by your browser.
There are two general ways to solve this problem. Either you maintain more than one developer key and somehow pick the right one to use when you load the Google Maps library, or you force people to always use the URL that is associated with your developer key by silently fixing bad URLs.
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 7: Extreme Google Maps Hacks
So far, we've seen the power and ease with which Google Maps can show nearly anything on a map, from your vacation photos to a hypothetical nuclear explosion. Now it's time for us to take Google Maps hacks to the next level by adding whole new feature sets and APIs. In this chapter, we'll supplement the missing features of Google Maps in various ways, by turning street addresses into map coordinates, generating dynamic icons using Google's polyline service, adding new controls to bring in background imagery from around the 'Net, and even creating our own custom background tiles! These hacks go far above and beyond anything that even Google could have imagined or intended for Google Maps—that's why we call them "Extreme Google Maps Hacks."
The Google Maps API won't do it for you, but there are other ways to find the coordinates of a given street address.
As we've seen all through this book, Google Maps makes it easy to make custom maps of anything for which you have a latitude and a longitude. However, people don't tend to think of places in terms of geographic coordinates; more often, people commonly know and refer to places by a street or mailing address. In order to find and show these places on a map, we need to be able to turn a given address into the corresponding latitude/longitude coordinates. The process of turning addresses into map coordinates is generally referred to as geocoding.
Unfortunately, for all the great things that the Google Maps API offers, the very common task of geocoding street addresses simply isn't among them. Although the Google Maps webUI will show you the location of an address, often with great accuracy, the problem is that Google doesn't own this data and has been unable to negotiate permission with its data providers to offer address lookups as a service in the API. Furthermore, screen-scraping the Google Maps results page is strictly a no-no, according to the Terms of Use. If you want to stay legit—and not risk angry takedown letters from you-know-who—how can you get the lat/long coordinates for a given street address?
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 62–70: Introduction
So far, we've seen the power and ease with which Google Maps can show nearly anything on a map, from your vacation photos to a hypothetical nuclear explosion. Now it's time for us to take Google Maps hacks to the next level by adding whole new feature sets and APIs. In this chapter, we'll supplement the missing features of Google Maps in various ways, by turning street addresses into map coordinates, generating dynamic icons using Google's polyline service, adding new controls to bring in background imagery from around the 'Net, and even creating our own custom background tiles! These hacks go far above and beyond anything that even Google could have imagined or intended for Google Maps—that's why we call them "Extreme Google Maps Hacks."
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 the Latitude and Longitude of a Street Address
The Google Maps API won't do it for you, but there are other ways to find the coordinates of a given street address.
As we've seen all through this book, Google Maps makes it easy to make custom maps of anything for which you have a latitude and a longitude. However, people don't tend to think of places in terms of geographic coordinates; more often, people commonly know and refer to places by a street or mailing address. In order to find and show these places on a map, we need to be able to turn a given address into the corresponding latitude/longitude coordinates. The process of turning addresses into map coordinates is generally referred to as geocoding.
Unfortunately, for all the great things that the Google Maps API offers, the very common task of geocoding street addresses simply isn't among them. Although the Google Maps webUI will show you the location of an address, often with great accuracy, the problem is that Google doesn't own this data and has been unable to negotiate permission with its data providers to offer address lookups as a service in the API. Furthermore, screen-scraping the Google Maps results page is strictly a no-no, according to the Terms of Use. If you want to stay legit—and not risk angry takedown letters from you-know-who—how can you get the lat/long coordinates for a given street address?
Fortunately, within the United States, the Census Bureau collects street address information as part of its constitutionally assigned duties of enumerating the populace of the country every ten years. What's more, the Census Bureau publishes this information in the public domain, in the form of the TIGER/Line data set. This data is freely available from the Census Bureau web site at http://www.census.gov/geo/www/tiger/. As of 2004, updated versions are published twice a year.
The problem is that the TIGER/Line data set is composed of 3,233 separate ZIP files, one for each county in the entire United States. The entire data set is 4.3 GB compressed and runs to almost 16 GB uncompressed. That's a lot of data to struggle with if you just want to look up a few lousy addresses. This is where
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Read and Write Markers from a MySQL Database
Keep track of almost anything with Google Maps and a relational database.
Adding a map of something new to Google Maps is good fun, but there is a lot of data already in SQL databases that is just begging to be mapped. This tutorial describes the way the Subfinder application, at http://www.map-server.com/googlemaps/subfinder.php, is integrated with a MySQL database using PHP. The Subfinder is itself an extension of the Who Locations site at http://www.map-server.com/googlemaps/wholocations2.php, which is described in a tutorial at http://www.map-server.com/googlemaps/tutorial.html. Figure 7-2 shows a map of the sites that any fan of The Who must know about.
There are easier ways to get points on a Google Map, but to integrate with a MySQL database you will need:
  1. An Apache web server running PHP and MySQL. (Other web server software with PHP and MySQL will probably do as well.)
  2. A table in your database with lat, long, and description columns.
  3. Some basic HTML and PHP knowledge.
We are going to use PHP to dynamically create an HTML document with the appropriate Google Maps JavaScript code. One of the functions shown in this sample is the option for users to add their own locations, with additional attributes, into the database. The value of one of the attribute determines the type of marker placed.
Figure 7-2: A map for Who fans
The database can be recreated with this snippet of SQL:
	CREATE TABLE subfinder (
	  id int(11) NOT NULL auto_increment,
	  lat decimal(10,6) NOT NULL default '0.000000',
	  lon decimal(10,6) NOT NULL default '0.000000',
	  desc varchar(255) NOT NULL default '',
	  url varchar(255) NOT NULL default '',
	  marker char(1) NOT NULL default '',
	  PRIMARY KEY (id)
	) TYPE=MyISAM;
If you save this into the file create_subfinder.sql, you can create a new database and this table with the following commands:
	
	$ mysqladmin create sub_db
	$ mysql sub_db < create_subfinder.sql
As you can see, there are fields for the latitude and longitude values, a description, URL (which will of course be displayed as a link), and a marker field. The value of the marker field will determine the type of marker placed. This application, which lists submarines visible on the Google Maps photos, makes a distinction between submarines that are in active duty (
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Build Custom Icons on the Fly
Using libraries that extend the Google Maps API in various ways, you can quickly achieve powerful results.
The XMaps library is a set of extensions to the Google Maps API. As of this writing, the library builds on the Google Maps API to add many capabilities that the API itself does not provide. As of this writing, the additional features provided by XMaps include filled polygons, text along polylines, and custom icons and markers. For this hack, we will see how to easily create new icons by making use of the XIcon and XMarker classes from XMaps. The XMaps library lives on the Web at http://xmaps.busmonster.com/.
The XIcon class is similar to Google's GIcon class, but it automates some of the steps necessary to create icons, making it simpler to make new icons on the fly. You could do the same thing that the XIcon class does by using a server-side script, but here we are using something that does not require any extra server horsepower or bandwidth from you. XIcon objects are limited in that they are a filled concave polygon (e.g., the outline of a car, lion, or circle), but you have the advantage of being able to specify the color, size, opacity, and any text on it on the fly.
The GIcon class makes use of a set of pre-rendered PNG images stored on a server somewhere. The default GIcon uses three images from Google Ride Finder to create its resulting image: the reddish-orange marker image, a nearly transparent version of that same image (for click detection on IE), and a mostly transparent shadow image. Figure 7-3 shows the parts of this pre-rendered icon.
Figure 7-3: Google Maps pushpin icon parts: (a) the pushpin image, (b) the shadow, (c) the click target for IE, and (d) the resulting icon
Instead of using pre-rendered images, an XIcon's images are created on the fly by using the existing (but unofficial) service that Google Maps already uses to draw polylines. Using this service, we can actually draw images of any color and opacity. By specifying the outline of the icon shape, the XIcon class can create the necessary images for you (including the shadow image). For example, if we wanted to create a rounded box icon, we could come up with a list of points for the outline, give them to
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 More Imagery with a WMS Interface
What's a pretty face like you doing on the geospatial web?
The Google Maps service is cool, the user interface is wonderful, the API is a joy, and the maps are pretty, but there is more to the world of mapping than what fits on one company's massive server farm.
The Open Geospatial Consortium (OGC) has defined a number of interoperability standards for web mapping applications. The simplest to understand is the Web Mapping Service (WMS) specification. In Google Maps terms, you would ask a WMS server for a tile that contains something like a Google Map or Satellite image. The key is that the WMS is not limited to the data that Google Maps maintains. There are WMS servers with things from Landsat imagery to topographic (elevation) data to habitat data. WMS requests are normally made by programs, but you can assemble a request by hand.
If you put this URL into your browser:
	http://wms.jpl.nasa.gov/wms.cgi?request=GetMap&layers
	   =global_mosaic_base&srs=EPSG:4326&bbox=-87.90,24.38,-76.65,30.01
	   &FORMAT=image/png&width=600&height=400&styles=pseudo
you will get the image of Florida shown in Figure 7-6.
Figure 7-6: Florida as shown by a WMS request
This looks a lot like a Google Maps tile. Even without understanding the format of a WMS request, you can look at that URL and get some information. For example, it has a bbox (or bounding box) that covers the area from 87.9 W to 76.65 W and 24.38 N to 30.01 N, which happens to be most of Florida.
You can make a request to a WMS server for a map that covers a certain area. But what is a map? WMS returns a raster (an image) for the selected area and for selected features. WMS Servers report what their capabilities are, what sorts of information they contain, and WMS clients can then select the layers they want to show.
David Knight has written a JavaScript extension library that you can insert into your own Google Maps page to let you browse through tiles from a WMS server using the Google Maps user interface. For an example of this, visit the Global Coordinate 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!
Add Your Own Custom Map
This time, it's personal.
Well, as everyone else has written in this book, those Google Maps sure are pretty. Then again, there is always room for improvement right? And sometimes Google's maps just don't highlight the right information. To really spice things up, you may want to add your own map…a map that looks the way you want it to look. This off-API hack shows you how to add your own custom map. In "Serve Custom Map Imagery" [Hack #67] , you'll get a script to serve custom map tiles, and finally in "Automatically Cut and Name Custom Map Tiles" [Hack #68] , there is a script to quickly make the thousands of little images you will need to display your map.
There are plenty of cool reasons to add your own map images. In creating the NYC Subway Google Map hack (http://www.onnyturf.com/subwaymap.php), I felt that Google's polylines were not elegant enough, and they were hard to see on top of Google's orange/green default map. To make the subway lines easier to see against the streetscape and to make the lines look nicer, I decided to add a custom map type that I illustrated, as you can see from Figure 7-14.
Another great use of adding your own map is using it as a semi-transparent overlay on the other map images. Figure 7-15 shows the street map layered on top of the satellite map, with a semi-transparent setting allowing you to see the relationship between the two. You can do this sort of thing with your own custom map too.
Creating this transparency effect is outside the scope of this tutorial. You can learn how to add transparency by looking at the source of the example above, which can be found at http://www.kokogiak.com/gmaps-transparencies.html. You will need to know these basics on adding a custom map in order to add transparency in that way.
Figure 7-14: Custom map for NYC subway map hack
There are four simple things you will need to do to add your own map.
  • Create a new map type.
  • Tell the map where it can find the images for your new type.
  • Customize your map's type button.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Serve Custom Map Imagery
You can serve your own custom tiles to Google Maps with a simple script.
If you've created a custom map layer [Hack #66] , you need a way to serve requests for tiles. This hack describes a PHP script to serve Google Maps compatible imagery.
Every time you drag the map around in the window, the Google Map application requests whatever tiles it needs in order to show more of the map. It does this by passing three values to the server for each tile it needs: an X coordinate value, a Y coordinate value, and a Zoom value. For each tile it needs, the map application sends a set of these three values.
Our image serving script uses the three values sent by the Google Map application to dynamically create paths to the appropriate image required to fill in a space in the map window. Our script is kept in a file named index.php. It assumes that tiles have been created and named by the naming standards described in "Automatically Cut and Name Custom Map Tiles" [Hack #68] .
With a little fancy footwork we can also use our script to send generic filler tiles to the map when we don't have custom tiles for a requested area. In the most common case, you will probably want to create a custom map that covers a small area, and not the whole globe. Therefore you will probably need to use some filler tiles where your map does not cover an area or zoom level. We can use our image serving script to determine when we don't have an appropriate custom tile and need to send a filler tile.
If you decide that you do need to make tiles for the whole planet, be sure to read "How Big Is the World?" [Hack #16] first!
To understand this script, we'll start with the whole thing and then break it down. Here is the full script that goes in our file index.php:
	<?php
	       define("NO_DATA", "./no_data.gif");
	       define("ZOOM_IN", "./zoom_in.gif");
	       define("ZOOM_OUT", "./zoom_out.gif");

	       $x = $_GET["x"];
	       $y = $_GET["y"];
	       $z = $_GET["zoom"];

	       $filename = "./nycmaps/${x}_${y}_${z}.gif";
	       if ( $z < 2 ) {
	           $content = file_get_contents( ZOOM_OUT );
	       }else if ( $z > 5 ){
	           $content = file_get_contents( ZOOM_IN );
	       }else if ( is_numeric($x) && is_numeric($y) && is_numeric($z)
	         && file_exists( $filename ) ){
	                   $content = file_get_contents( $filename );
	       }else{
	           $content = file_get_contents( NO_DATA );
	       }
	       header("Content-type: image/gif");
	       echo $content;
	?>
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Automatically Cut and Name Custom Map Tiles
Make time to really enjoy a cup of coffee.
Google Maps are made of dozens to thousands of tile images, depending on the zoom level. At the distant zoom levels you only need a few images to cover a large area. For example, the NYC Subway Map uses 49 images to cover the greater metropolitan area at zoom level 5. But at the closer zoom levels, thousands of images are required. It takes more than 3500 images to cover the NYC metropolitan area at zoom level 2. "How Big Is the World?" [Hack #16] discusses the amount of disk space needed to tile the entire planet. Figure 7-21 shows a custom tile at zoom level 5, while Figure 7-22 shows part of the same area at zoom level 2.
Creating and then uniquely naming each of these images for even a small part of our world would be a daunting task if you had to do it by hand. That's why we use a script to do this. The following hack will show you how to configure a batch processing script to use with Photoshop 7 or CS that will carve all the tiles you need from one big image into hundreds of smaller GIFs and name them exactly as you need them named.
Before we set up and use our script we need to know a few things about Google's tiles. As we learned in "Serve Custom Map Imagery" [Hack #67] , each 256 X 256–pixel tile has a longitude, a latitude, and a zoom value. These are represented in the URL by the x, y, and zoom values.
Figure 7-21: A custom tile at zoom level 5
Figure 7-22: A custom tile at zoom level 2
Here is what a tile path from Google looks like:
	http://mt.google.com/mt?v=w2.4&x=1206&y=1539&zoom=5
So how do you get the x, y, and zoom values? Fortunately you don't have to get all the x, y, and z values for all your images. We only need to get a set of values for one tile and from there we can derive all the other values we need.
We start with a limited area for our map because we assume you don't want to remap the whole world, but just a small corner of it. All we need then is to get the x, y, and z value of the upper-left corner tile of our map area and know how many tiles wide and high our map area is. For simplicity, our example map is square so that the area width and height are the same, but you could tweak this script to work with rectangular areas. Once we know the upper-left corner tile values, our batch processing script will calculate the rest for us.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Cluster Markers at High Zoom Levels
When necessary, avoid cramming a map too full of markers by clustering them together.
Two major problems can occur when you try to put too many markers on a Google Map at once. First, the large quantity of markers can take a long time to render, consume a lot of memory in the browser, and pretty much slow things to a crawl. We address this particular problem to some degree in "Show Lots of Stuff—Quickly" [Hack #59] . The other, equally serious problem is a more general matter of good digital cartography, in that too many markers placed too close together can make the markers difficult to click and the map difficult to interpret. Both problems can be fairly effectively solved by first applying a clustering algorithm to a large data set of points, and then by tailoring the display of the point clusters, such that they become readily identifiable and easy to interact with.
To experiment with this idea, we took over 600 waypoints from Rich Gibson's GPS receiver, representing the highlights of several years' worth of travels. Since Rich lives in northern California, most of the points are centered around the western United States, while the remainder are scattered from Mexico to Massachusetts to Venice, Italy. We figured that about 600 points would qualify as too many to show on a map at once, but not so many as to make experimentation difficult.
The solution that we eventually hit upon for visualizing all of Rich's travels at once can be seen at http://mappinghacks.com/projects/gmaps/cluster.html, as shown in Figure 7-27. The standard Google Maps marker is used to represent a cluster of points, roughly bounded by the red box around the marker. Clicking on a marker pans and zooms the map to the area covered by that cluster. As you get closer in, more localized clusters appear, eventually resolving into the small Google Ridefinder markers, which represent Rich's individual waypoints. Clicking on one of these smaller markers opens a small info window, showing the name and coordinates of the waypoint, as shown in Figure 7-28 .
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Will the Kids Barf? (and Other Cool Ways to Use Google Maps)
Google Maps Hacks are turning up everywhere; here are some things we just didn't have time to cover fully.
My kids get sick on curvy roads. It is just a fact of life. One measure of the curviness of a road is the detour index. This is the ratio of the shortest road distance and the straight-line distance. Some mathematicians also call this the "fractal dimension of the polyline."
	Detour Index = road distance ÷ straight line distance X 100
We can get the road distance by calculating the driving directions and grabbing that distance. Figure 7-30 shows it is 68.1 miles from Cloverdale to Mendocino.
See "How Far Is That? Go Beyond Driving Directions" [Hack #12] for different ways to calculate the straight-line distance. I used our sample tool at http://mappinghacks.com/projects/gmaps/lines.html. Be careful to measure the same distance! I noted the start and stop points of the Google route and tried to match those in calculating the straight-line distance as shown in Figure 7-31.
Figure 7-30: From Cloverdale to Mendocino is 68.1 miles on the road
Figure 7-31: Straight-line distance from Cloverdale to Mendocino is 55.1 miles
The straight-line distance is 55.1 miles, so the detour index is 68.1÷55.1 X 100=123.6.
Through careful analysis of four or five trips, as partially described in Mapping Hacks, I've determined that a detour index over about 120 is a recipe for carsick fun. If you are a motorcyclist looking for curves, you can use the number for your own ends. But remember, as the heartless half of this book's writing team says, "For some people, motion sickness is no laughing matter. For the rest of us, it is."
We really wanted to turn this into a Google Maps demo that you could experiment with yourself, but we just didn't have the time!
One of the painful challenges in writing this book during the heady days of the release of the official API was that we just could not keep up with all of the cool work that was being done, much less contribute to it ourselves. We'd watch our email, and the Google Maps API mailing list, and Del.icio.us, and more cool "must include" hacks appeared than we could possibly ever write about. Here are a few of the coolest.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!

Return to Google Maps Hacks