Geocoding in C# using Google Maps

If you have ever worked on a project involving maps (such as Google Maps), the chances are you will need to get the longitude and latitude for an address or set of addresses that have been entered by a user or have been supplied by a customer in a file or database. Well, the nice people at Google have provide a very simple HTTP service for geocoding (getting the longitude and latitude) for a given address. It works for any address in any country and importantly (because I live in the UK) is very accurate for full UK postcodes and yields results similar to the client-side GLocalSearch JavaScript class (anyone wanting to do client-side geocoding should check out GLocalSearch!).

The following C# method demonstrates calling the Google Maps geocoding service. It uses LINQ to XML to parse the results (XDocument is so much better than the old XmlDocument class!).

You can download the code using the link at the bottom of this post.

Geocoding Example

The following method accepts a comma separated address string and returns the longitude and latitude.

public static GeocoderLocation Locate(string query)
{
   WebRequest request = WebRequest
      .Create("http://maps.googleapis.com/maps/api/geocode/xml?sensor=false&address="
         + HttpUtility.UrlEncode(query));

   using (WebResponse response = request.GetResponse())
   {
      using (Stream stream = response.GetResponseStream())
      {
         XDocument document = XDocument.Load(new StreamReader(stream));

         XElement longitudeElement = document.Descendants("lng").FirstOrDefault();
         XElement latitudeElement = document.Descendants("lat").FirstOrDefault();

         if (longitudeElement != null && latitudeElement != null)
         {
            return new GeocoderLocation
            {
               Longitude = Double.Parse(longitudeElement.Value, CultureInfo.InvariantCulture),
               Latitude = Double.Parse(latitudeElement.Value, CultureInfo.InvariantCulture)
            };
         }
      }
   }

   return null;
}

Location Class

public class GeocoderLocation
{
  public double Longitude { get; set; }

  public double Latitude { get; set; }
}

It couldn't be easier! Thank you Google Maps.

July update to fix KML API (via http://maps.google.com/maps?output=kml&q=) being removed and no longer working.

The Google KML API was removed in July 2012 and this post used to use that API. However, I've updated the code to use the new Google API. The old XML service used to use the URL http://maps.google.com/maps?output=kml&q=. Also, with the new API the longitude and latitude elements have been renamed lng and lat and the namespace of http://earth.google.com/kml/2.0 has been dropped. Like the KML API, the method still does not require an API key which is good news!