If you want a simple way to translate written descriptions of places into latitudes and longitudes, the Google Geocoding API offers an easy solution. Up to now, I’d been allowing users to restrict searches geographically by entering a bounding box (the latitude and longitude of two corners) or the WOE codes (see Using “Where on Earth” Codes in Flickr).

The Trackr Panel includes an input labeled place. It accepts a textual description of a place, like a city, neighborhood, landmark, or ZIP code (try “Dupont Circle” or “National Mall”). That value is simply passed to the PHP program via the URL; it’s the PHP program that must now decipher the place.

You can handle web services with the simplexml_load_file function, which turns an XML file (the web service) into an object. The following code breaks this down thus, first building the web service’s URL, then seeing if it can get a valid XML response:

define("MAPS_HOST", "maps.google.com");
define("KEY", Your-key-here);
$base_url = "http://" . MAPS_HOST . "/maps/geo?output=xml" . "&key=" . KEY;
$request_url = $base_url . "&q=" . urlencode($_GET["place"]);
$xml = simplexml_load_file($request_url) or die("url not loading");

The full code makes the call inside a loop, where it keeps trying until it finds success or definitive failure. The code for Your-key-here is gotten when you register with Google. (You need permission to use this API.) When successful, the call returns a bounding box for the place:

$bbox = $xml->Response->Placemark->ExtendedData->LatLonBox->asXML(); 

So now we can send this bounding box to the Flickr API, the flickr.photos.search method.

We then use the locations of the returned photos to build an entirely new bounding box, one that fits only the retrieved photos. This bounding box is then sent to the Google Maps JavaScript API. And of course the end result, the borders of the map displayed, are inevitably larger than the bounding box we sent, since the map is zoomed to ensure it fits within the viewport.

And it works! Go to the Trackr Panel to play with it for your own photos.

Using the Google Geocoding API

Leave a Reply