Saturday, April 28, 2012

C# Function to get Geo Coding Using Google Maps Geocoding API


 using  Newtonsoft.Json;
 


    public class GeoLocation
    {
        public decimal Lat { getset; }
 
        public decimal Lng { getset; }
    }
 
    public class GeoGeometry
    {
        public GeoLocation Location { getset; }
    }
 
    public class GeoResult
    {
        public GeoGeometry Geometry { getset; }
    }
 
    public class GeoResponse
    {
        public string Status { getset; }
 
        public GeoResult[] Results { getset; }
    }


private Dictionary<stringstring> getLatLong(string address)
    {
  Dictionary<stringstring> diclatlong = new Dictionary<stringstring>();
  string url = "http://maps.googleapis.com/maps/api/geocode/json?address=" 
                + Server.UrlEncode( address) + "&sensor=false";
        WebResponse response = null;
        try
        {
         HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
         request.Method = "GET";
         response = request.GetResponse();
         if (response != null)
         {
           string str = null;
           using (Stream stream = response.GetResponseStream())
           {
            using (StreamReader streamReader = new StreamReader(stream))
            {
             str = streamReader.ReadToEnd();
            }
           }
            GeoResponse geoResponse = JsonConvert.DeserializeObject<GeoResponse>(str);
            if (geoResponse.Status == "OK")
            {
             int count = geoResponse.Results.Length;
             for (int i = 0; i < count; i++)
             {
        diclatlong.Add("Lat", geoResponse.Results[i].Geometry.Location.Lat.ToString());
        diclatlong.Add("Lng", geoResponse.Results[i].Geometry.Location.Lng.ToString());
             }
            }
            else
             {
              diclatlong.Add("Lat""");
              diclatlong.Add("Lng""");
             }
            }
        }
        catch
        { throw new Exception ("JSON response failed."); }
        finally
        {
            if (response != null)
                {
                response.Close ();
                response = null;
                }
        }
        return diclatlong;
    }


I have used JSon.NET Library

1 comment:

Unknown said...

Thanks a lot Kiran. :-). Awesome piece of code you wrote there.