Convert Latitude and Longitude to a Street Address and Map
I sometimes see latitude and longitude numbers provided in the response from API calls, and often, you want to pass this information to the user. But, it’s much nicer to convert these geo coordinates to an actual street address. This is called Reverse Geocoding and there are a number of web services that allow you to do this. For example, Google, Twitter, and Flickr all have methods in their API to reverse geocode. Let’s explore how that is done and since we are talking about the user experience, let’s also generate a static map of the geo location.
Consider the following geographical coordinates:
Using a Google Maps API call we can make a request to transform these lat and long numbers into a street address:
The response has a lot of information but formatted_address gives you 2-98 Brosnan St, San Francisco, CA 94103, USA. Twitter API also has a geo method called reverse_geocode that gives you a similar result:
The response does not give you a street address but it does give you the neighborhood and city (Mission Dolores, San Francisco), plus it gives you id information that you can use to retrieve tweets from this location. The great thing about these two calls is that they do not require an API key.
Flickr, on the other hand, does require a key and uses a method called flickr.places.findByLatLon. Here is the same call with the Flickr API:
The response gives you a woeid (Where on Earth IDentifier) and the neighborhood (The Hub, San Francisco, CA, US). It makes sense to use Flickr and Twitter if you are also retrieving pictures and tweets but clearly Google gives you the most detailed location information and the API call does not need to be authenticated. Google also has a static map service that you can also use without an API key to show the user where that location exists on a map.
There are some parameters you can tweak, like zoom, scale, image size, etc, but this call works pretty well:
and it will generate this static map image (just place that url into an IMG SRC):
So, next time you are working with geo coordinates, translate them to an address and map for a better user experience.