Pages

Wednesday, August 28, 2013

Convert Address to Lattitude/Longitude (using Geocoding Google maps)

Geocoding example using javascript and C#


Google provides easy way to convert human readable address into Latitude/Longitude set.
[Detail]
A Geocoding API request:

http://maps.googleapis.com/maps/api/geocode/output?parameters

Google response are either of the following format
1. JSON
2. XML
Following code will tell long story in short:

1. Using Javascript:

//address format for the most accurate lat/lang ( address + ', ' + city + ', ' + state + ' ' + zip) 
eg:- 2842 Crescent Park Ln, Atlanta, GA 30339
 <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&libraries=places,geometry"></script>

 findLatlong(address){ 
var address="2842 Crescent Park Ln, Atlanta, GA 30339";
  var point=null;
 geocoder.geocode({ 'address': address }, function (results, status) {
              
                if (status == google.maps.GeocoderStatus.OK) {

                    point.lat = results[0].geometry.location.lat();
                    point.lng = results[0].geometry.location.lng();
               
                }
                else {
              
                    alert('Geocode was not successful for the following reason: '
+ status);
                }
 
            });
return point;
}
[Note: geocode is called asynchronously so mind the flow. ]

2.Using C#:

The following c# code explains how to call Google geocode service and parse the response using LINQ to XML:

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

   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 point
            {
               Longitude = Double.Parse(longitudeElement.Value, CultureInfo.InvariantCulture),
               Latitude = Double.Parse(latitudeElement.Value, CultureInfo.InvariantCulture)
            };
         }
      }
   }

   return null;
}

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

Hope this helps , Cheers !

No comments:

Post a Comment