16 October 2011 Google Maps; Geo-coordinates CI Team

 

To find out the exact coordinates of an address there are numerous services available. Some ways goes through Javascript and the Google Maps “Plugin” others are reachable via a surface. The “smartest” (and cheapest / for free) alternative is via Google Maps Geocoding API.

Request / Response

The structure of the request is quite easy – via Http GET:

http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true

The Address has to be Url-Encoded.

After this call a JSON will answer. There is also the option with XML. In my case I’ve decided for JSON and parse the whole thing on a JSON.NET library with a “LINQ-ro-JSON” (or something like that).

If something is found (and Google founds something every time even how weird the places are formatted) than you are going to receive an answer like this:

image1376

 

About the code:

public class GeoCoordinates
    	{
        	public string Lat { get; set; }
        	public string Lng { get; set; }
        	public string Name { get; set; }
		}

		public GeoCoordinates GetCoordinates(string location)
        {
            string url = "http://maps.googleapis.com/maps/api/geocode/json?address=" + HttpUtility.UrlEncode(location) +
                         "&sensor=true";
            WebClient client = new WebClient();
            JObject result = JObject.Parse(client.DownloadString(url));
            JToken status;
            result.TryGetValue("status", out status);

            if(status.ToString() == "ZERO_RESULTS")
                return new GeoCoordinates();

            var geoCood = result.SelectToken("results[0].geometry.location");

            string lat = geoCood.SelectToken("lat").ToString();
            string lng = geoCood.SelectToken("lng").ToString();
            return new GeoCoordinates() { Name = location,  Lat = lat, Lng = lng };
        }

All in all it’s quite easy.

What kinds of restrictions are possible?

It’s only possible to geocode 2500 addresses per day. Beside according to the Terms of Service it’s only allowed if you set a Google Map into the UI or don’t abuse with the API (for example take a lot of files without any sense). More information’s on Google.