Created
January 13, 2012 10:41
-
-
Save FelicePollano/1605478 to your computer and use it in GitHub Desktop.
AdderssResolver
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class AddressResolver | |
| { | |
| string language = "en-GB"; | |
| public AddressResolver() | |
| { | |
| } | |
| public AddressResolver(string language) | |
| { | |
| this.language = language; | |
| } | |
| [DataContract] | |
| class AddressInfo | |
| { | |
| [DataMember(Name = "formatted_address")] | |
| public string FormattedAddress { get; set; } | |
| } | |
| [DataContract] | |
| class ResultInfo | |
| { | |
| [DataMember(Name = "results")] | |
| public AddressInfo[] Info { get; set; } | |
| } | |
| readonly string URITemplate = "http://maps.googleapis.com/maps/api/geocode/json?latlng={0},{1}&sensor=true&language={2}"; | |
| public void AsyncResolve(double lat, double lon, Action<string[]> callback) | |
| { | |
| WebClient client = new WebClient(); | |
| client.DownloadStringCompleted += (s, e) => | |
| { | |
| if (e.Error == null) | |
| { | |
| var ainfo = ReadToObject<ResultInfo>(e.Result); | |
| callback(ainfo.Info.Select(k => k.FormattedAddress).ToArray()); | |
| } | |
| else | |
| { | |
| callback(new[] { "ERROR:" + e.Error.Message }); | |
| } | |
| }; | |
| client.DownloadStringAsync(new Uri(GetFormattedUri(lat, lon))); | |
| } | |
| public static T ReadToObject<T>(string json) where T:class | |
| { | |
| MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)); | |
| DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); | |
| T res = ser.ReadObject(ms) as T; | |
| ms.Close(); | |
| return res; | |
| } | |
| private string GetFormattedUri(double lat, double lon) | |
| { | |
| return string.Format(CultureInfo.InvariantCulture, URITemplate, lat, lon,language); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment