Saturday, September 17, 2011

Converting Street Addresses into Latitude and Longitude Using Google

I have recently been working on a mobile application and came across an interesting problem. In my app, I am using Google's MapKit to display cities on a map, just there is a problem with the way the MapKit works. Unlike Google Maps where you can simply look up an address and have the map refocus on the area, the MapKit does not have the functionality to search for an address. Instead, a map needs its frame to be centered on a specific geographical latitude and longitude coordinate, along with other parameters for determining the width and height of the area to display.

The data that I'm using only contains cities and their respective states or countries, so I needed to find a way to display these areas in my map view. Luckily, Google seems to have already thought up an easy solution and provides a Geocoding Request server.

The idea is simple, just push a request to the server with your parameters in the url and the server utilizes the advanced algorithm behind Google Maps to respond with detailed information about the address. Better yet, you get to choose if you want the response to be in XML or JSON format!

So here is the url to use:

http://maps.google.com/maps/api/geocode/output?address=&sensor=

You simply plug in the type of format (xml OR json) you would like in the output field, append your address after the address= field (don't forget to use a + symbol for any spaces), and append either true or false for the sensor= field depending on if the machine you are requesting with has a location sensor (a mobile device would).

So for example, check out this link:
http://maps.google.com/maps/api/geocode/json?address=11700+Plaza+America+Drive,Reston,Virginia&sensor=false

Lots of good stuff in there, it even corrects the address into the "official" address format. But most importantly for me, it contains a lat and lng location:

"location": {
"lat": 38.9521550,
"lng": -77.3500670
}

Now let's just confirm that:
http://maps.google.com/maps?q=38.9521550,+-77.3500670

As you can see, Google does a pretty spot-on job at this conversion, and its fast and easy to do. With this data, you could use your machine's location sensor to determine your current location and then determine a linear distance between the two geographical points, or even calculate directions!

You can check out their full API at:
http://code.google.com/apis/maps/documentation/geocoding/index.html

Cheers!