Skip to content

Instantly share code, notes, and snippets.

@OndeVai
Created March 14, 2012 20:53
Show Gist options
  • Save OndeVai/2039435 to your computer and use it in GitHub Desktop.
Save OndeVai/2039435 to your computer and use it in GitHub Desktop.
Calling Google Geo Coding Service with Json.Net Server Side
public interface IGeoLocationService
{
Location GetLocation(string street, string city, string state, string zip);
Location GetLocation(string address);
}
public class GoogleGeoLocationService : IGeoLocationService
{
public Location GetLocation(string street, string city, string state, string zip)
{
var address = string.Format("{0},+{1},+{2}+{3}",
Encode(street), Encode(city), Encode(state), Encode(zip));
return GetLocation(address);
}
public Location GetLocation(string address)
{
var url = string.Format("http://maps.googleapis.com/maps/api/geocode/json?address={0}&sensor=false",
address);
try
{
// prepare the web page we will be asking for
var request = (HttpWebRequest) WebRequest.Create(url);
request.Method = "GET";
request.ContentType = "application/json; charset=utf-8";
// execute the request
string responseVal;
using (var response = (HttpWebResponse) request.GetResponse())
{
var resStream = response.GetResponseStream();
using (var reader = new StreamReader(resStream))
{
responseVal = reader.ReadToEnd();
}
}
var o = JObject.Parse(responseVal);
var resultGeo = o.SelectToken("results[0].geometry");
var lat = (decimal) resultGeo.SelectToken("location.lat");
var lng = (decimal) resultGeo.SelectToken("location.lng");
return new Location(lat, lng);
}
catch (Exception e)
{
ThrowInvalid(url, e);
}
return null;
}
private static void ThrowInvalid(string url, Exception ex)
{
throw new InvalidOperationException(string.Format("GeoCoder could not find lat long for {0}", url), ex);
}
private static string Encode(string input)
{
return HttpUtility.UrlEncode(input.Replace(" ", "+"));
}
}
public class Location
{
public Location(decimal lat, decimal lng)
{
Lng = lng;
Lat = lat;
}
public decimal Lat { get; private set; }
public decimal Lng { get; private set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment