public void MakeRequest(string text, Action complete) { if (IsInProgress) { return; } IsInProgress = true; Task.Run(delegate { var request = new GeocodingRequest(Projection, text); GeocodingResultVector results = Service.CalculateAddresses(request); int count = results.Count; Addresses.Clear(); for (int i = 0; i < count; i++) { GeocodingResult result = results[i]; Addresses.Add(result); } IsInProgress = false; complete(); }); }
[ValidateInput(false)] // Some user locations are UTF encoded (e.g., ö => ö) public JsonResult Index(string locs) { // NOTE: Switched from ';'-delimited since encoded UTF chars end with those. string[] locations = (locs ?? "").Split(new[] { "||" }, StringSplitOptions.RemoveEmptyEntries); List <Task> locationLookups = new List <Task>(); ConcurrentDictionary <string, GeocodingResult> results = new ConcurrentDictionary <string, GeocodingResult>(); foreach (string location in locations) { string currentLocation = location; locationLookups.Add(Task.Factory.StartNew(() => { GeocodingResult result = null; try { result = getGeocoding(currentLocation); } catch { // TODO: Log lookup errors. } results.TryAdd(currentLocation, result); })); } Task.WaitAll(locationLookups.ToArray()); // Put into results[location] => { lat, lng }. IDictionary massagedDictionary = results.ToDictionary(kvp => kvp.Key, kvp => kvp.Value != null && kvp.Value.Coordinates != null ? new { lat = kvp.Value.Coordinates.Latitude, lng = kvp.Value.Coordinates.Longitude } : (object)null); return(Json(new { results = massagedDictionary }, JsonRequestBehavior.AllowGet)); }
void OnResultClick(object sender, AdapterView.ItemClickEventArgs e) { OnEditingEnded(false); GeocodingResult result = ContentView.Adapter.Items[e.Position]; ShowResult(result); }
private void OutputGeocodingResult(IOutputProvider outputProvider, HttpContext context, APIRequestParams filter) { GeocodingResult result = null; //get or get and cache result if (HttpContext.Current.Cache["Geocoding_" + filter.HashKey] != null && filter.EnableCaching) { result = (GeocodingResult)HttpContext.Current.Cache["Geocoding_" + filter.HashKey]; } else { var geocoder = new GeocodingHelper(); geocoder.IncludeExtendedData = true; //result = geocoder.GeolocateAddressInfo_OSM(filter.Address); result = geocoder.GeolocateAddressInfo_Google(filter.Address); HttpContext.Current.Cache.Add("Geocoding_" + filter.HashKey, result, null, Cache.NoAbsoluteExpiration, new TimeSpan(1, 0, 0), CacheItemPriority.Normal, null); } //send API response if (filter.IsEnvelopedResponse) { var responseEnvelope = new APIResponseEnvelope(); responseEnvelope.Data = result; outputProvider.GetOutput(context.Response.OutputStream, responseEnvelope, filter); } else { outputProvider.GetOutput(context.Response.OutputStream, result, filter); } }
public GeocodingResult Lookup(string location) { if (location == null) { return(null); } GeocodingResult result = null; using (IDbConnection connection = new SqlConnection(this.ConnectionString)) { connection.Open(); dynamic data = connection.Query(selectByLocation, new { location = location.ToUpperInvariant() }).FirstOrDefault(); if (data != null) { Coordinates coords = null; if (data.Latitude != null && data.Longitude != null) { coords = new Coordinates() { Latitude = data.Latitude, Longitude = data.Longitude }; } result = new GeocodingResult() { Location = data.Location, Coordinates = coords }; } } return(result); }
public void RowSelected(UITableView tableView, NSIndexPath indexPath) { (ContentView as GeocodingView).FinishEditing(); GeocodingResult result = Geocoding.Addresses[indexPath.Row]; ShowResult(result); }
void ShowResult(GeocodingResult result) { string title = ""; string description = result.GetPrettyAddress(); bool goToPosition = true; ContentView.GeocodingSource.ShowResult(ContentView.MapView, result, title, description, goToPosition); }
public GeocodingResult GeolocateAddressInfo_MapquestOSM(string address) { GeocodingResult result = new GeocodingResult(); result.Service = "MapQuest Open"; string url = "http://open.mapquestapi.com/geocoding/v1/address?key=" + ConfigurationManager.AppSettings["MapQuestOpen_API_Key"] + "&location=" + Uri.EscapeDataString(address.ToString()); if (IncludeQueryURL) { result.QueryURL = url; } string data = ""; try { WebClient client = new WebClient(); client.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1"); client.Encoding = Encoding.GetEncoding("UTF-8"); data = client.DownloadString(url); if (IncludeExtendedData) { result.ExtendedData = data; } if (data == "[]") { System.Diagnostics.Debug.WriteLine("No geocoding results:" + url); result.ResultsAvailable = false; } else { JObject o = JObject.Parse(data); var locations = o["results"][0]["locations"]; if (locations.Any()) { var item = o["results"][0]["locations"][0]["latLng"]; result.Latitude = double.Parse(item["lat"].ToString()); result.Longitude = double.Parse(item["lng"].ToString()); result.ResultsAvailable = true; } else { result.ResultsAvailable = false; } } } catch (Exception) { // } return(result); }
protected virtual async Task<GeocodingResult> DoGeocodingQuery(string addressToGeocode) { string message; var result = new GeocodingResult(); var geocoder = new GoogleGeocoder(); List<GoogleAddress> addresses = new List<GoogleAddress>(); while (true) { try { //Wait if needed to avoid making geocoding calls faster than we should await GeocodingRateLimiter.WaitNextAsync(); //Geocode the address and break out of the loop if successful. Log.Debug($"Geocoding '{addressToGeocode}'"); addresses.AddRange(await geocoder.GeocodeAsync(addressToGeocode)); break; } catch (GoogleGeocodingException ex) when (ex.Status == GoogleStatus.OverQueryLimit) { //If we're making queries too quickly, slow down. Log.Debug($"OverQueryLimit @ '{addressToGeocode}'"); GeocodingRateLimiter.IncreaseDelay(); } } if (addresses.Count <= 0) { message = $"Warning: No results found for address: {addressToGeocode}."; } else if (addresses.Count > 1) { StringBuilder multiples = new StringBuilder(); for (int i = 0; i < addresses.Count; i++) { multiples.Append($"\n[Result {i + 1} ====> {addresses[i].FormattedAddress}]"); } message = $"Warning: Multiple addresses found for {addressToGeocode}: {multiples}"; } else if (addresses[0].IsPartialMatch) { message = $"Warning: Partial match for address: {addressToGeocode} => [{addresses[0].FormattedAddress}]."; } else { result.Location = addresses[0].Coordinates; return result; } //If we get down here, there was some kind of problem. Store the details and log the warning before returning. result.StateInfo = new LookupStateInfo<GoogleAddress> { Message = message, PossibleResults = addresses }; Log.Warn(message); return result; }
public GeocodingResult GeolocateAddressInfo_OSM(string address) { GeocodingResult result = new GeocodingResult(); result.Service = "OSM Nominatim"; if (String.IsNullOrWhiteSpace(address)) { result.ResultsAvailable = false; } else { string url = "http://nominatim.openstreetmap.org/search?q=" + address.ToString() + "&format=json&polygon=0&addressdetails=1&email=" + ConfigurationManager.AppSettings["OSM_API_Key"]; if (IncludeQueryURL) { result.QueryURL = url; } string data = ""; try { //enforce rate limiting System.Threading.Thread.Sleep(1000); //make api request WebClient client = new WebClient(); client.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1"); client.Encoding = Encoding.GetEncoding("UTF-8"); data = client.DownloadString(url); if (IncludeExtendedData) { result.ExtendedData = data; } if (data == "[]") { result.ResultsAvailable = false; } else { JArray o = JArray.Parse(data); result.Latitude = double.Parse(o.First["lat"].ToString()); result.Longitude = double.Parse(o.First["lon"].ToString()); result.Attribution = o.First["licence"].ToString(); result.ResultsAvailable = true; } } catch (Exception) { //oops } } return(result); }
void ShowResult(GeocodingResult result) { var title = ""; var description = result.GetPrettyAddress(); var goToPosition = true; var source = (ContentView as GeocodingView).ObjectSource; source.ShowResult(ContentView.MapView, result, title, description, goToPosition); }
public override void OnMapClicked(MapClickInfo mapClickInfo) { MapPos position = mapClickInfo.ClickPos; var request = new ReverseGeocodingRequest(projection, position); var meters = 125.0f; request.SearchRadius = meters; GeocodingResultVector results = new GeocodingResultVector(); try { results = Service.CalculateAddresses(request); } catch (Exception e) { Carto.Utils.Log.Error("Reverse geocoding failed: " + e.Message); } GeocodingResult result = null; int count = results.Count; // Scan the results list. If we found relatively close point-based match, // use this instead of the first result. // In case of POIs within buildings, this allows us to hightlight POI instead of the building if (count > 0) { result = results[0]; } for (int i = 0; i < count; i++) { GeocodingResult other = results[i]; // 0.8f means 125 * (1.0 - 0.9) = 12.5 meters (rank is relative distance) if (other.Rank > 0.9f) { string name = other.Address.Name; // Points of interest usually have names, others just have addresses if (!string.IsNullOrWhiteSpace(name)) { result = other; break; } } } ResultFound?.Invoke(result, EventArgs.Empty); }
public static string GetPrettyAddress(this GeocodingResult result) { var parsed = ""; var address = result.Address; if (address.Name.IsNotEmpty()) { parsed += address.Name; } if (address.Street.IsNotEmpty()) { parsed += parsed.AddCommaIfNecessary(); parsed += address.Street; } if (address.HouseNumber.IsNotEmpty()) { parsed += " " + address.HouseNumber; } if (address.Neighbourhood.IsNotEmpty()) { parsed += parsed.AddCommaIfNecessary(); parsed += address.Neighbourhood; } if (address.Locality.IsNotEmpty()) { parsed += parsed.AddCommaIfNecessary(); parsed += address.Locality; } if (address.County.IsNotEmpty()) { parsed += parsed.AddCommaIfNecessary(); parsed += address.County; } if (address.Region.IsNotEmpty()) { parsed += parsed.AddCommaIfNecessary(); parsed += address.Region; } if (address.Country.IsNotEmpty()) { parsed += parsed.AddCommaIfNecessary(); parsed += address.Country; } return(parsed); }
public void Store(GeocodingResult geocodingResult) { if (geocodingResult == null) { return; } Coordinates coords = geocodingResult.Coordinates; decimal? latitude = coords != null ? coords.Latitude : (decimal?)null; decimal? longitude = coords != null ? coords.Longitude : (decimal?)null; using (IDbConnection connection = new SqlConnection(this.ConnectionString)) { connection.Open(); connection.Execute(tryCatchInsertSql, new { location = geocodingResult.Location.ToUpperInvariant(), latitude = latitude, longitude = longitude }); } }
public GeocodingResult GeolocateAddressInfo_Google(string address) { GeocodingResult result = new GeocodingResult(); result.Service = "Google Maps"; if (!String.IsNullOrWhiteSpace(address)) { string url = "http://maps.googleapis.com/maps/api/geocode/json?sensor=true&address=" + address; if (IncludeQueryURL) { result.QueryURL = url; } using (System.Net.WebClient wc = new System.Net.WebClient()) { wc.Encoding = System.Text.Encoding.UTF8; wc.Headers["User-Agent"] = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)"; try { string queryResult = wc.DownloadString(url); if (IncludeExtendedData) { result.ExtendedData = queryResult; } JavaScriptSerializer jss = new JavaScriptSerializer(); var parsedResult = jss.Deserialize <dynamic>(queryResult); string lat = parsedResult["results"][0]["geometry"]["location"]["lat"].ToString(); string lng = parsedResult["results"][0]["geometry"]["location"]["lng"].ToString(); string desc = parsedResult["results"][0]["formatted_address"].ToString(); result.Latitude = Double.Parse(lat); result.Longitude = Double.Parse(lng); result.Address = desc; result.ResultsAvailable = true; } catch (Exception) { //failed to geocode result.ResultsAvailable = false; } } } return(result); }
private void btnSearch_Click(object sender, EventArgs e) { var request = new GeocodingRequest(); request.Address = textLocation.Text; request.Sensor = "false"; var response = GeocodingService.GetResponse(request); if (response.Status == ServiceResponseStatus.Ok) { currentSelectedLocation = response.Results.First(); } updateMap(); }
private async Task <GeocodingResult> ResolveAddressAsync(string lq) { GeocodingResult coords = null; try { coords = await _geocoder.ResolveAddressAsync(lq); } catch (Exception ex) { _telemetryClient.TrackException(ex); } return(coords); }
private void OutputGeocodingResult(IOutputProvider outputProvider, HttpContext context, APIRequestParams filter) { GeocodingResult result = null; //get or get and cache result /*if (context.Cache["Geocoding_" + filter.HashKey] != null && filter.EnableCaching) * { * result = (GeocodingResult)context.Cache["Geocoding_" + filter.HashKey]; * } * else * { * * * //context.Cache.Add("Geocoding_" + filter.HashKey, result, null, Cache.NoAbsoluteExpiration, new TimeSpan(1, 0, 0), CacheItemPriority.Normal, null); * }*/ var geocoder = new GeocodingHelper(_settings); geocoder.IncludeExtendedData = false; if (!string.IsNullOrEmpty(filter.Address)) { result = geocoder.GeolocateAddressInfo_MapquestOSM(filter.Address); } else if (filter.Latitude != null && filter.Longitude != null) { result = geocoder.ReverseGecode_MapquestOSM((double)filter.Latitude, (double)filter.Longitude, new ReferenceDataManager()); if (!result.ResultsAvailable) { result = geocoder.ReverseGecode_OSM((double)filter.Latitude, (double)filter.Longitude, new ReferenceDataManager()); } } //send API response if (filter.IsEnvelopedResponse) { var responseEnvelope = new APIResponseEnvelope(); responseEnvelope.Data = result; outputProvider.GetOutput(context, context.Response.Body, responseEnvelope, filter); } else { outputProvider.GetOutput(context, context.Response.Body, result, filter); } }
private GeocodingResult getGeocoding(string location) { GeocodingResult result = this.GeocodingCache.Lookup(location); if (result == null) { GeocodingLookupServiceResult lookupResult = this.GeocodingLookupService.Geocode(location); if (lookupResult.Status == GeocodingLookupServiceResult.LookupStatus.Ok || lookupResult.Status == GeocodingLookupServiceResult.LookupStatus.ZeroResults) { // Cache successful results (including no-such-address results). this.GeocodingCache.Store(lookupResult); } result = lookupResult; } return(result); }
void OnFoundResult(object sender, EventArgs e) { GeocodingResult result = (GeocodingResult)sender; if (result == null) { Alert("Couldn't find any addresses. Are you sure you have downloaded the region you're trying to reverse geocode?"); return; } string title = ""; string description = result.ToString(); bool goToPosition = false; var source = (ContentView as ReverseGeocodingView).ObjectSource; source.ShowResult(ContentView.MapView, result, title, description, goToPosition); }
public GeocodingResult Lookup(string location) { if (location == null) { return null; } GeocodingResult result = null; using (IDbConnection connection = new SqlConnection(this.ConnectionString)) { connection.Open(); dynamic data = connection.Query(selectByLocation, new { location = location.ToUpperInvariant() }).FirstOrDefault(); if (data != null) { Coordinates coords = null; if (data.Latitude != null && data.Longitude != null) { coords = new Coordinates() { Latitude = data.Latitude, Longitude = data.Longitude }; } result = new GeocodingResult() { Location = data.Location, Coordinates = coords }; } } return result; }
void OnEditingEnded(bool geocode) { ContentView.CloseKeyboard(); ContentView.HideTable(); if (geocode) { string text = ContentView.Field.Text; GeocodingClient.MakeRequest(text, delegate { if (GeocodingClient.HasAddress) { GeocodingResult result = GeocodingClient.Addresses[0]; ShowResult(result); } }); } ContentView.ClearInput(); }
private void btnSearch_Click(object sender, EventArgs e) { //var request = new GeocodingRequest(); //SpeechRecognizer recognizer = new SpeechRecognizer(); //recognizer.SpeechRecognized += // new EventHandler<SpeechRecognizedEventArgs>(sre_SpeechRecognized); //request.Address = textLocation.Text; //request.Address= //var response = GeocodingService.GetResponse(request); //if (response.Status == ServiceResponseStatus.Ok) { // currentSelectedLocation = response.Results.First(); //} //updateMap(); var request = new GeocodingRequest(); //request.Address = list //foreach (String lists in list) //{ // request.Address = lists; // //textLocation.AppendText(" " + lists); //} request.Address = textLocation.Text; request.Sensor = "false"; var response = GeocodingService.GetResponse(request); if (response.Status == ServiceResponseStatus.Ok) { currentSelectedLocation = response.Results.First(); } updateMap(); }
void OnGeocodingResultFound(object sender, EventArgs e) { GeocodingResult result = (GeocodingResult)sender; if (result == null) { RunOnUiThread(delegate { string text = "Couldn't find any addresses. Please try again"; ContentView.Banner.Show(text); }); return; } string title = ""; string description = result.ToString(); bool goToPosition = false; var view = ContentView as BaseGeocodingView; view.GeocodingSource.ShowResult(ContentView.MapView, result, title, description, goToPosition); }
public bool ShouldReturn(UITextField textField) { (ContentView as GeocodingView).FinishEditing(); string text = (ContentView as GeocodingView).InputField.Text; Geocoding.MakeRequest(text, delegate { InvokeOnMainThread(delegate { if (Geocoding.HasAddress) { GeocodingResult result = Geocoding.Addresses[0]; ShowResult(result); } else { Alert("Unable to find any results. What did you just type in?"); } }); }); return(true); }
public void MakeRequest(string text, Action complete) { if (IsInProgress) { return; } IsInProgress = true; Task.Run(delegate { var request = new GeocodingRequest(Projection, text); GeocodingResultVector results = new GeocodingResultVector(); try { results = Service.CalculateAddresses(request); } catch (Exception e) { Carto.Utils.Log.Error("Geocoding failed: " + e.Message); } int count = results.Count; Addresses.Clear(); for (int i = 0; i < count; i++) { GeocodingResult result = results[i]; Addresses.Add(result); } IsInProgress = false; complete(); }); }
public static void ShowResult(this LocalVectorDataSource source, MapView map, GeocodingResult result, string title, string description, bool goToPosition) { source.Clear(); var builder = new BalloonPopupStyleBuilder(); builder.LeftMargins = new BalloonPopupMargins(0, 0, 0, 0); builder.TitleMargins = new BalloonPopupMargins(6, 3, 6, 3); builder.CornerRadius = 5; // Make sure this label is shown on top of all other labels builder.PlacementPriority = 10; FeatureCollection collection = result.FeatureCollection; int count = collection.FeatureCount; MapPos position = new MapPos(); Geometry geometry; for (int i = 0; i < count; i++) { geometry = collection.GetFeature(i).Geometry; var color = new Carto.Graphics.Color(0, 100, 200, 150); var pointBuilder = new PointStyleBuilder(); pointBuilder.Color = color; var lineBuilder = new LineStyleBuilder(); lineBuilder.Color = color; var polygonBuilder = new PolygonStyleBuilder(); polygonBuilder.Color = color; VectorElement element = null; if (geometry is PointGeometry) { element = new Point(geometry as PointGeometry, pointBuilder.BuildStyle()); } else if (geometry is LineGeometry) { element = new Line(geometry as LineGeometry, lineBuilder.BuildStyle()); } else if (geometry is PolygonGeometry) { element = new Polygon(geometry as PolygonGeometry, polygonBuilder.BuildStyle()); } else if (geometry is MultiGeometry) { var collectionBuilder = new GeometryCollectionStyleBuilder(); collectionBuilder.PointStyle = pointBuilder.BuildStyle(); collectionBuilder.LineStyle = lineBuilder.BuildStyle(); collectionBuilder.PolygonStyle = polygonBuilder.BuildStyle(); element = new GeometryCollection(geometry as MultiGeometry, collectionBuilder.BuildStyle()); } if (element != null) { position = geometry.CenterPos; source.Add(element); } } if (goToPosition) { map.SetFocusPos(position, 1.0f); map.SetZoom(16, 1.0f); } var popup = new BalloonPopup(position, builder.BuildStyle(), title, description); source.Add(popup); }
private static void DeliverResultToReceiver(GeocodingResult resultCode, List<string> addresses) { foreach (var item in addresses) { Console.WriteLine("{0} - {1}", resultCode.ToString(), item); } }
private static void DeliverResultToReceiver(GeocodingResult resultCode, string message) { Console.WriteLine("{0} - {1}", resultCode.ToString(), message); }
public GeocodingResult ReverseGecode_OSM(double latitude, double longitude, ReferenceDataManager refDataManager) { GeocodingResult result = new GeocodingResult(); result.Service = "Nominatim OSM"; string url = $"https://nominatim.openstreetmap.org/reverse?format=json&lat={latitude}&lon={longitude}&zoom=18&addressdetails=1"; if (IncludeQueryURL) { result.QueryURL = url; } string data = ""; try { WebClient client = new WebClient(); client.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1"); client.Encoding = Encoding.GetEncoding("UTF-8"); data = client.DownloadString(url); /* e.g.: * { * "place_id": 101131804, * "licence": "Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright", * "osm_type": "way", * "osm_id": 61267076, * "lat": "-32.1685328505288", * "lon": "115.9882328723638", * "display_name": "Eleventh Road, Haynes, Armadale, Western Australia, 6112, Australia", * "address": { * "road": "Eleventh Road", * "suburb": "Haynes", * "town": "Armadale", * "state": "Western Australia", * "postcode": "6112", * "country": "Australia", * "country_code": "au" * }, * "boundingbox": [ * "-32.1689883", * "-32.1619497", * "115.9805577", * "115.9887699" * ] * } * */ if (IncludeExtendedData) { result.ExtendedData = data; } else { System.Diagnostics.Debug.WriteLine(data); } if (data == "{}") { System.Diagnostics.Debug.WriteLine("No geocoding results:" + url); result.ResultsAvailable = false; } else { JObject o = JObject.Parse(data); var item = o["address"]; result.AddressInfo = new AddressInfo(); result.AddressInfo.Title = item["road"]?.ToString(); result.AddressInfo.Postcode = item["postcode"]?.ToString(); result.AddressInfo.AddressLine1 = item["road"]?.ToString(); result.AddressInfo.AddressLine2 = item["suburb"]?.ToString(); result.AddressInfo.Town = item["town"]?.ToString(); result.AddressInfo.StateOrProvince = item["state"]?.ToString(); var countryCode = item["country_code"]?.ToString(); var country = refDataManager.GetCountryByISO(countryCode); if (country != null) { result.AddressInfo.CountryID = country.ID; } result.Latitude = latitude; result.Longitude = longitude; result.Attribution = "Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright"; result.AddressInfo.Latitude = latitude; result.AddressInfo.Longitude = longitude; result.ResultsAvailable = true; } } catch (Exception) { // } return(result); }
public GeocodingResult ReverseGecode_MapquestOSM(double latitude, double longitude, ReferenceDataManager refDataManager) { GeocodingResult result = new GeocodingResult(); result.Service = "MapQuest Open"; string url = "http://open.mapquestapi.com/geocoding/v1/reverse?location=" + latitude + "," + longitude + "&key=" + _settings.ApiKeys.MapQuestOpenAPIKey; if (IncludeQueryURL) { result.QueryURL = url; } string data = ""; try { WebClient client = new WebClient(); client.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1"); client.Encoding = Encoding.GetEncoding("UTF-8"); data = client.DownloadString(url); if (IncludeExtendedData) { result.ExtendedData = data; } else { System.Diagnostics.Debug.WriteLine(data); } if (data == "[]") { System.Diagnostics.Debug.WriteLine("No geocoding results:" + url); result.ResultsAvailable = false; } else { JObject o = JObject.Parse(data); var locations = o["results"][0]["locations"]; if (locations.Any()) { var item = o["results"][0]["locations"][0]; result.AddressInfo = new AddressInfo(); result.AddressInfo.Title = item["street"]?.ToString(); result.AddressInfo.Postcode = item["postalCode"]?.ToString(); result.AddressInfo.AddressLine1 = item["street"]?.ToString(); if (item["adminArea5Type"]?.ToString() == "City") { result.AddressInfo.Town = item["adminArea5"]?.ToString(); } if (item["adminArea3Type"]?.ToString() == "State") { result.AddressInfo.StateOrProvince = item["adminArea3"]?.ToString(); } if (item["adminArea3Type"]?.ToString() == "State") { result.AddressInfo.StateOrProvince = item["adminArea3"]?.ToString(); } if (item["adminArea1Type"]?.ToString() == "Country") { var countryCode = item["adminArea1"]?.ToString(); var country = refDataManager.GetCountryByISO(countryCode); if (country != null) { result.AddressInfo.CountryID = country.ID; } } result.Latitude = latitude; result.Longitude = longitude; result.Attribution = "Portions © OpenStreetMap contributors"; // using mapquest open so results are from OSM result.AddressInfo.Latitude = latitude; result.AddressInfo.Longitude = longitude; result.ResultsAvailable = true; } else { result.ResultsAvailable = false; } } } catch (Exception) { // } return(result); }
public void Update(GeocodingResult item) { label.Text = item.GetPrettyAddress(); LayoutSubviews(); }