Monday, February 21, 2011

GeoCoding with C# and Google Geocoding API V3

Geocoding is the process of finding associated geographic coordinates (often expressed as latitude and longitude) from other geographic data, such as street addresses, or zip codes (postal codes). (read more in wikipedia)

Today I'll give a short example of C# application in which we will use the newest version of Google Geocoding API V3. You can compare it with similar C++ geocoding example.

When you perform a geocoder request, you can specify which output type to use. The available options are JSON, XML, KML and CSV. We will be requesting and handling XML data.

If you are searching for example with JSON output format I have written one here.

For example, if you wanted to find the coordinates of house located at 1600 Amphitheatre Parkway, Mountain View, CA, you would request the following URL: (http://maps.googleapis.com/maps/api/geocode/xml?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false).

The response will be processed with XPath and coordinates will be printed to console.

The full working example is in the following code:

using System;
using System.Net;
using System.Xml.XPath;

namespace GeoCoderApiV3App1
{
    class Program
    {
        static void Main(string[] args)
        {
            string url = "http://maps.googleapis.com/maps/api/geocode/xml?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false";
            
            WebResponse response = null;
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "GET";
                response = request.GetResponse();
                if (response != null)
                {
                    XPathDocument document = new XPathDocument(response.GetResponseStream());
                    XPathNavigator navigator = document.CreateNavigator();
                    
                    // get response status
                    XPathNodeIterator statusIterator = navigator.Select("/GeocodeResponse/status");
                    while (statusIterator.MoveNext())
                    {
                        if (statusIterator.Current.Value != "OK")
                        {
                            Console.WriteLine("Error: response status = '" + statusIterator.Current.Value + "'");
                            return;
                        }
                    }
                    
                    // get results
                    XPathNodeIterator resultIterator = navigator.Select("/GeocodeResponse/result");
                    while (resultIterator.MoveNext())
                    {
                        Console.WriteLine("Result: ");
                        
                        XPathNodeIterator formattedAddressIterator = resultIterator.Current.Select("formatted_address");
                        while (formattedAddressIterator.MoveNext())
                        {
                            Console.WriteLine(" formatted_address: " + formattedAddressIterator.Current.Value);
                        }
                        
                        XPathNodeIterator geometryIterator = resultIterator.Current.Select("geometry");
                        while (geometryIterator.MoveNext())
                        {
                            Console.WriteLine(" geometry: ");
                            
                            XPathNodeIterator locationIterator = geometryIterator.Current.Select("location");
                            while (locationIterator.MoveNext())
                            {
                                Console.WriteLine("     location: ");
                                
                                XPathNodeIterator latIterator = locationIterator.Current.Select("lat");
                                while (latIterator.MoveNext())
                                {
                                    Console.WriteLine("         lat: " + latIterator.Current.Value);
                                }
                                
                                XPathNodeIterator lngIterator = locationIterator.Current.Select("lng");
                                while (lngIterator.MoveNext())
                                {
                                    Console.WriteLine("         lng: " + lngIterator.Current.Value);
                                }
                            }
                            
                            XPathNodeIterator locationTypeIterator = geometryIterator.Current.Select("location_type");
                            while (locationTypeIterator.MoveNext())
                            {
                                Console.WriteLine("         location_type: " + locationTypeIterator.Current.Value);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                Console.WriteLine("Clean up");
                if (response != null)
                {
                    response.Close();
                    response = null;
                }
            }
            
            Console.WriteLine("Done.");
            Console.ReadLine();
        }
    }
}

8 comments:

  1. Just what I was looking for. Thanks for your help.

    ReplyDelete
  2. Same, exactly what i was looking too after long hour of research, it's the solution to beginners, just Thanks.

    ReplyDelete
  3. How to check the output of the above code using Visual C# 2010 express ?

    ReplyDelete
  4. I will create complete solution and will upload it to GitHub repository. Please check this post after few days. I hope this will help you to solve your problems.

    ReplyDelete
  5. how is it possible to add your client id to get more request then the default per day? I used a client id in v2 but now in v3 if i add the &clientid=... i receive no results. Thank you

    ReplyDelete
  6. Thanks! Exactly what I was looking for.

    ReplyDelete
  7. This is great. Thank you.

    ReplyDelete
  8. Thanks for the article

    ReplyDelete