Thursday, April 9, 2015

Geocoding in C# using Google Maps

I was curious about KML and other things to do with Googlemap.  I found this great post about
how to change a street address to a lat/lng.

Sample web service request to get lat/lng:
http://maps.googleapis.com/maps/api/geocode/xml?sensor=false&address=...

C# to use the web service

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

[Serializable]
public class GeocoderLocation
{
   public double Longitude { get; set; }
   public double Latitude { get; set; }
 
   public override string ToString()
   {
      return String.Format("{0}, {1}", Latitude, Longitude);
   }
}
 
source:
 

No comments:

Post a Comment