/// <summary> /// Handle tap event on the map; displays callouts showing the address for a tapped search result /// </summary> private async void MyMapView_GeoViewTapped(object sender, Esri.ArcGISRuntime.Xamarin.Forms.GeoViewInputEventArgs e) { try { // Search for the graphics underneath the user's tap IReadOnlyList <IdentifyGraphicsOverlayResult> results = await MyMapView.IdentifyGraphicsOverlaysAsync(e.Position, 12, false); // Return gracefully if there was no result if (results.Count < 1 || results.First().Graphics.Count < 1) { return; } // Reverse geocode to get addresses IReadOnlyList <GeocodeResult> addresses = await _geocoder.ReverseGeocodeAsync(e.Location); // Get the first result GeocodeResult address = addresses.First(); // Use the city and region for the Callout Title string calloutTitle = address.Attributes["City"] + ", " + address.Attributes["Region"]; // Use the metro area for the Callout Detail string calloutDetail = address.Attributes["MetroArea"].ToString(); // Define the callout CalloutDefinition calloutBody = new CalloutDefinition(calloutTitle, calloutDetail); // Show the callout on the map at the tapped location MyMapView.ShowCalloutAt(e.Location, calloutBody); } catch (Exception ex) { await Application.Current.MainPage.DisplayAlert("Error", ex.ToString(), "OK"); } }
/// <summary> /// Handle tap event on the map; displays callouts showing the address for a tapped search result. /// </summary> private async void MyMapView_GeoViewTapped(object sender, GeoViewInputEventArgs e) { // Search for the graphics underneath the user's tap. try { IReadOnlyList <IdentifyGraphicsOverlayResult> results = await _myMapView.IdentifyGraphicsOverlaysAsync(e.Position, 12, false); // Return gracefully if there was no result. if (results.Count < 1 || results.First().Graphics.Count < 1) { return; } // Reverse geocode to get addresses. IReadOnlyList <GeocodeResult> addresses = await _geocoder.ReverseGeocodeAsync(e.Location); // Get the first result. GeocodeResult address = addresses.First(); // Use the city and region for the Callout Title. string calloutTitle = address.Attributes["City"] + ", " + address.Attributes["Region"]; // Use the metro area for the Callout Detail. string calloutDetail = address.Attributes["MetroArea"].ToString(); // Define the callout. CalloutDefinition calloutBody = new CalloutDefinition(calloutTitle, calloutDetail); // Show the callout on the map at the tapped location. _myMapView.ShowCalloutAt(e.Location, calloutBody); } catch (Exception ex) { new UIAlertView("Error", ex.ToString(), (IUIAlertViewDelegate)null, "OK", null).Show(); } }
/// <summary> /// Handle tap event on the map; displays callouts showing the address for a tapped search result /// </summary> private async void MyMapView_GeoViewTapped(object sender, GeoViewInputEventArgs e) { // Search for the graphics underneath the user's tap IReadOnlyList <IdentifyGraphicsOverlayResult> results = await MyMapView.IdentifyGraphicsOverlaysAsync(e.Position, 12, false); // Return gracefully if there was no result if (results.Count < 1 || results.First().Graphics.Count < 1) { return; } // Reverse geocode to get addresses IReadOnlyList <GeocodeResult> addresses = await _geocoder.ReverseGeocodeAsync(e.Location); // Get the first result GeocodeResult address = addresses.First(); // Use the city and region for the Callout Title String calloutTitle = address.Attributes["City"] + ", " + address.Attributes["Region"]; // Use the metro area for the Callout Detail String calloutDetail = address.Attributes["MetroArea"].ToString(); // Use the MapView to convert from the on-screen location to the on-map location MapPoint point = MyMapView.ScreenToLocation(e.Position); // Define the callout CalloutDefinition calloutBody = new CalloutDefinition(calloutTitle, calloutDetail); // Show the callout on the map at the tapped location MyMapView.ShowCalloutAt(point, calloutBody); }
private async Task <Symbol?> SymbolForResult(GeocodeResult r) { if (ResultSymbolStyle != null && r.Attributes.ContainsKey(LocatorIconAttributeKey) && r.Attributes[LocatorIconAttributeKey] is string typeAttrs) { if (Locator.Uri?.ToString() == WorldGeocoderUriString && ResultSymbolStyle.StyleName == "Esri2DPointSymbolsStyle") { var firstResult = await ResultSymbolStyle.GetSymbolAsync(new[] { typeAttrs.ToString().Replace(' ', '-').ToLower() }); if (firstResult != null) { return(firstResult); } } var symbParams = new SymbolStyleSearchParameters(); symbParams.Names.Add(typeAttrs.ToString()); symbParams.NamesStrictlyMatch = false; var symbolResult = await ResultSymbolStyle.SearchSymbolsAsync(symbParams); if (symbolResult.Any()) { return(await symbolResult.First().GetSymbolAsync()); } } return(DefaultSymbol); }
/// <summary> /// Gets the map point corresponding to the text in the location textbox. /// If the text is 'Current Location', the returned map point will be the device's location. /// </summary> private async Task <MapPoint> GetSearchMapPoint(string locationText) { // Get the map point for the search text. if (locationText != "Current Location") { // Geocode the location. IReadOnlyList <GeocodeResult> locations = await _geocoder.GeocodeAsync(locationText); // return if there are no results. if (!locations.Any()) { return(null); } // Get the first result. GeocodeResult result = locations.First(); // Return the map point. return(result.DisplayLocation); } else { // Get the current device location. return(MyMapView.LocationDisplay.Location.Position); } }
private async void CalculateRoute(GeocodeResult from, GeocodeResult to) { using (RouteServiceClient client = new RouteServiceClient("CustomBinding_IRouteService")) { RouteRequest request = new RouteRequest { Credentials = new Credentials() { ApplicationId = Resources.BingApiKey }, Waypoints = new ObservableCollection <Waypoint> { ConvertResultToWayPoint(@from), ConvertResultToWayPoint(to) }, Options = new RouteOptions { RoutePathType = RoutePathType.Points }, }; try { RouteResult = client.CalculateRoute(request).Result; } catch (Exception) { await this.interactionService.ShowMessageBox("Sorry", $"Could not find: {this.From}"); return; } } GetDirections(); }
private async Task <SearchResult> GeocodeResultToSearchResult(GeocodeResult r) { var symbol = await SymbolForResult(r); string?subtitle = null; if (SubtitleAttributeKey != null && r.Attributes.ContainsKey(SubtitleAttributeKey) && r.Attributes[SubtitleAttributeKey] is string subtitleString) { subtitle = subtitleString; } var viewpoint = r.Extent == null ? null : new Mapping.Viewpoint(r.Extent); var graphic = new Graphic(r.DisplayLocation, r.Attributes, symbol); CalloutDefinition callout = new CalloutDefinition(graphic) { Text = r.Label, DetailText = subtitle }; return(new SearchResult(r.Label, subtitle, this, graphic, viewpoint) { CalloutDefinition = callout }); }
private async Task <GeocodeResult> GeocodeAddress(string address) { GeocodeResult result = null; using (GeocodeServiceClient client = new GeocodeServiceClient("CustomBinding_IGeocodeService")) { GeocodeRequest request = new GeocodeRequest(); request.Credentials = new Credentials() { ApplicationId = Resources.BingApiKey }; request.Query = address; try { result = client.Geocode(request).Results[0]; } catch (Exception) { await this.interactionService.ShowMessageBox("Sorry", $"Could not find: {this.From}"); } } return(result); }
public async Task GeocodeAsync(SourceAddress source) { using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Accept.Add( new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); var response = await client.GetAsync(BuildUrlRequest(source)); if (response.IsSuccessStatusCode) { string content = await response.Content.ReadAsStringAsync(); AzureMapsGeocodeResult geocodeResult = JsonConvert.DeserializeObject <AzureMapsGeocodeResult>(content); GeocodeResult <Result> bestResult = GetBestGeocodeResult(geocodeResult, source); string freeformAddress = bestResult.Result == null ? "NULL" : bestResult.Result.Address.FreeformAddress; string resultType = bestResult.Result == null ? "NULL" : bestResult.Result.Type; ReportComparer.SaveAndDisplay(path, $"Azure Maps;{source.Id};{source.Address};{source.Locality};{source.PostalCode};{source.Country};{resultType};{freeformAddress};{bestResult.Status};{geocodeResult.Summary.NumResults}"); } else { //var error = await response.Content.ReadAsAsync<ErrorResponse>(); Console.WriteLine("Azure HTTP Error"); ReportComparer.SaveAndDisplay(path, $"Azure Maps;{source.Id};{source.Address};{source.Locality};{source.PostalCode};{source.Country};NULL;NULL;ZERO_RESULT;0"); } } }
private GeocodeResult <Result> GetBestGeocodeResult(AzureMapsGeocodeResult geocodeResult, SourceAddress source) { var result = new GeocodeResult <Result>(); if (geocodeResult.Results.Count == 0) { result.Status = "ZERO_RESULT"; return(result); } var best = geocodeResult.Results[0]; //The best result /*types: * Point Address (PAD):Indicates a precise street address * Points of Interest (POI):defines and locates residential, business and public postal addresses * */ if (best.Type.Equals("Point Address") || best.Type.Equals("POI")) { result.Status = best.Address.PostalCode.Equals(source.PostalCode) ? "OK" : "TO_CHECK"; } else { result.Status = "TO_CHECK"; } result.Result = best; return(result); }
public Address_Validated(GeocodeResult result, Validate_Address from) { Related_To_Validate_Address = from; GeocodeResult = result; Location = result.Locations.FirstOrDefault(); Address = result.Address; }
private Waypoint ConvertResultToWayPoint(GeocodeResult result) { Waypoint waypoint = new Waypoint(); waypoint.Description = result.DisplayName; waypoint.Location = result.Locations[0]; return(waypoint); }
private void client_GeocodeCompleted(object sender, GeocodeCompletedEventArgs e) { try { RoutingState state = e.UserState as RoutingState; GeocodeResult result = null; lock (StateSync) { if (_geoFailed) { return; } } if (e.Result.ResponseSummary.StatusCode != Bing.Geocode.ResponseStatusCode.Success || e.Result.Results.Count == 0) { lock (StateSync) { _geoFailed = true; } // Report geocode error. _uiDispatcher.BeginInvoke(() => Error(new RouteCalculationError(e))); return; } bool doneGeocoding = false; lock (StateSync) { // Only report on first result. result = e.Result.Results.First(); // Update state object ... when all the results are set, call route. state.Results[state.LocationNumber] = result; doneGeocoding = state.GeocodesComplete; } if (doneGeocoding && state.GeocodesSuccessful) { // Calculate the route. CalculateRoute(state.Results); } } catch (Exception ex) { lock (StateSync) { _geoFailed = true; } _uiDispatcher.BeginInvoke(() => Error(new RouteCalculationError(ex.Message, ex))); } }
public void FindAddressCandidatesWithoutTokenReturnsSuccess() { GeocodeParameters gcParams = CreateTestGeocodeParamsSingleLineBasic(); GeocodeService service = new GeocodeService(); GeocodeResult result = service.FindAddressCandidates(gcParams); Assert.IsInstanceOfType(result, typeof(GeocodeResult)); Assert.IsNotNull(result.candidates, "Candidates should not be null."); Assert.IsNotNull(result.spatialReference, "Spatial Reference should not be null."); }
public async Task <IActionResult> ReverseGeocode(double lat, double lng) { var address = await this._geoService.ReverseGeocodeAsync(lat, lng); GeocodeResult result = new GeocodeResult() { Latitude = lat, Longitude = lng, Address = address }; return(Ok(result)); }
private Waypoint GeocodeResultToWaypoint(GeocodeResult result) { return(new Waypoint() { Description = result.DisplayName, Location = new Location() { Latitude = result.Locations[0].Latitude, Longitude = result.Locations[0].Longitude } }); }
// // Copy/Paste Sample: http://open.mapquestapi.com/nominatim/v1/reverse?format=xml&lat=51.521435&lon=-0.162714 // public async Task <GeocodeResult> ReverseGeocode(double latitude, double longitude) { string URL = String.Format( "http://open.mapquestapi.com/nominatim/v1/reverse?format=xml&lat={0}&lon={1}", latitude.ToString(CultureInfo.InvariantCulture), longitude.ToString(CultureInfo.InvariantCulture)); string response = ""; using (var client = new HttpClient()) { response = await client.GetStringAsync(URL); client.Dispose(); } var searchresults = XElement.Parse(response); var resElement = searchresults.Elements("result").FirstOrDefault(); var addressElement = searchresults.Elements("addressparts").FirstOrDefault(); if (resElement != null && addressElement != null) { var countryCode = (string)addressElement.Element("country_code"); if (0 == String.Compare("at", countryCode, StringComparison.OrdinalIgnoreCase)) { // Only if City or Town is not available, we will fall back to the actual location name string locationName = (string)addressElement.Element("city"); if (String.IsNullOrWhiteSpace(locationName)) { locationName = (string)addressElement.Element("town"); if (String.IsNullOrWhiteSpace(locationName)) { locationName = (string)resElement; } } var result = new GeocodeResult() { Name = locationName, Latitude = MappingHelpers.ConvertDouble((string)resElement.Attribute("lat")), Longitude = MappingHelpers.ConvertDouble((string)resElement.Attribute("lon")) }; return(result); } } return(null); }
private async void updateSearch() { // Get the text in the search bar. string enteredText = MySearchBar.Text; // Clear existing marker. MyMapView.GraphicsOverlays[0].Graphics.Clear(); MyMapView.DismissCallout(); // Return if the textbox is empty or the geocoder isn't ready. if (String.IsNullOrWhiteSpace(enteredText) || _geocoder == null) { return; } try { // Get suggestions based on the input text. IReadOnlyList <GeocodeResult> geocodeResults = await _geocoder.GeocodeAsync(enteredText); // Stop if there are no suggestions. if (!geocodeResults.Any()) { await Application.Current.MainPage.DisplayAlert("No results", "No results found.", "OK"); return; } // Get the full address for the first suggestion. GeocodeResult firstSuggestion = geocodeResults.First(); IReadOnlyList <GeocodeResult> addresses = await _geocoder.GeocodeAsync(firstSuggestion.Label); // Stop if the geocoder does not return a result. if (addresses.Count < 1) { return; } // Show a graphic for the address. Graphic point = await GraphicForPoint(addresses.First().DisplayLocation); MyMapView.GraphicsOverlays[0].Graphics.Add(point); // Update the map extent to show the marker. MyMapView.SetViewpoint(new Viewpoint(addresses.First().Extent)); } catch (Exception e) { await Application.Current.MainPage.DisplayAlert("Error", e.ToString(), "OK"); } }
private void GeocodeLocationAndSave(Location matchedLocation) { // geocode - limit 900 per hour / one every 4 seconds var geocodeResult = new GeocodeResult(); var cityGeocodeResult = new GeocodeResult(); var successFlag = false; try { geocodeResult = _geocodeService.Geocode("", matchedLocation.StreetAddress, matchedLocation.City, matchedLocation.State, matchedLocation.Zip); successFlag = true; } catch (Exception e) { ReportErrors.AddError(string.Format("Unable to fetch GeocodeResult for {0} {1} {2} {3}", matchedLocation.StreetAddress, matchedLocation.City, matchedLocation.State, matchedLocation.Zip)); } try { cityGeocodeResult = _geocodeService.Geocode("", "", matchedLocation.City, matchedLocation.State, matchedLocation.Zip); successFlag &= true; } catch (Exception e) { ReportErrors.AddError(string.Format("Unable to fetch CityGeocodeResult for {0} {1} {2} {3}", matchedLocation.StreetAddress, matchedLocation.City, matchedLocation.State, matchedLocation.Zip)); } if (successFlag) { geocodeResult.SaveTo(matchedLocation); if (geocodeResult.IsSameAs(cityGeocodeResult)) { // geocode failure likely ReportErrors.AddError(string.Format("Geocode failure for location {0}", matchedLocation.LegacyId)); matchedLocation.IsFailedGeocode = true; } if (matchedLocation.Id == 0 && matchedLocation.LegacyId != "0") { _locationService.Insert(matchedLocation); } else { _locationService.Update(matchedLocation); } } }
public async Task <ActionResult> Index(RatingViewModel model) { try { // TODO: Add insert logic here GeolocationService service = new GeolocationService(); GeocodeResult result = await service.Geocode(model.Address); return(View("GeocodingResult", result.Geometry.Location)); } catch { return(View()); } }
/// <summary> /// Creates a basic search result for the given geocode result. /// </summary> private SearchResult GeocodeResultToSearchResult(GeocodeResult r) { string?subtitle = null; if (SubtitleAttributeKey != null && r.Attributes.ContainsKey(SubtitleAttributeKey)) { subtitle = r.Attributes[SubtitleAttributeKey]?.ToString(); } Mapping.Viewpoint?selectionViewpoint = r.Extent == null ? null : new Mapping.Viewpoint(r.Extent); return(new SearchResult(r.Label, subtitle, this, new Graphic(r.DisplayLocation, r.Attributes, DefaultSymbol), selectionViewpoint) { CalloutDefinition = DefaultCalloutDefinition }); }
public void CalculateAsync() { // Geocode locations in parallel. var results = new GeocodeResult[2]; // To location. var state1 = new RoutingState(results, 1, _to); GeocodeAddress(_to, state1); // From location. var state0 = new RoutingState(results, 0, _from); GeocodeAddress(_from, state0); }
public void FindAddressCandidatesMultiLineFull() { GeocodeParameters gcParams = CreateTestGeocodeParamsMultiFieldFull(); Dictionary <string, object> dictOutput = gcParams.ToDictionary(); var test = dictOutput.ToQueryString(); Assert.IsInstanceOfType(test, typeof(string), test); GeocodeService service = new GeocodeService(); GeocodeResult result = service.FindAddressCandidates(gcParams, this.Token); Assert.IsInstanceOfType(result, typeof(GeocodeResult)); Assert.IsNotNull(result.candidates, "Candidates should not be null."); Assert.IsNotNull(result.spatialReference, "Spatial Reference should not be null."); }
void geocodeService_ReverseGeocodeCompleted(object sender, ReverseGeocodeCompletedEventArgs e) { if (e.Cancelled || e.Error != null || e.Result.ResponseSummary.StatusCode != ResponseStatusCode.Success) { MessageBox.Show("Unable to complete the ReverseGeocode request"); return; } GeocodeResponse response = e.Result; if (response.Results.Count > 0) { GeocodeResult address = response.Results[0]; MessageBox.Show(address.DisplayName); } }
public void FindAddressCandidatesWithoutTokenForStorageThrowsException() { GeocodeParameters gcParams = CreateTestGeocodeParamsSingleLineBasic(); gcParams.forStorage = true; GeocodeService service = new GeocodeService(); try { GeocodeResult result = service.FindAddressCandidates(gcParams); } catch (Exception ex) { Assert.IsInstanceOfType(ex, typeof(GeocodeException)); } }
public void FindAddressCandidatesSingleLineBasic() { string singleLineBasicJson = "singleLine=614+E+Gorham+St&location=%5b-89.383%2c43.081%5d&outFields=NAME&forStorage=False&locationType=rooftop&f=json"; GeocodeParameters gcParams = CreateTestGeocodeParamsSingleLineBasic(); Dictionary <string, object> dictOutput = gcParams.ToDictionary(); string queryString = dictOutput.ToQueryString(); Assert.IsInstanceOfType(queryString, typeof(string), queryString); Assert.AreEqual(queryString, singleLineBasicJson); GeocodeService service = new GeocodeService(); GeocodeResult result = service.FindAddressCandidates(gcParams, this.Token); Assert.IsInstanceOfType(result, typeof(GeocodeResult)); Assert.IsNotNull(result.candidates, "Candidates should not be null."); Assert.IsNotNull(result.spatialReference, "Spatial Reference should not be null."); }
public void FindAddressCandidatesMultiLineBasic() { string multiLineBasicJson = "address=James+Madison+Park&address2=614+E+Gorham+St&address3=Basketball+courts&neighborhood=Downtown&city=Madison&subregion=Dane+County®ion=WI&postal=53703&countryCode=USA&location=%5b-89.383%2c43.081%5d&forStorage=False&locationType=rooftop&f=json"; GeocodeParameters gcParams = CreateTestGeocodeParamsMultiFieldBasic(); Dictionary <string, object> dictOutput = gcParams.ToDictionary(); var test = dictOutput.ToQueryString(); Assert.IsInstanceOfType(test, typeof(string), test); Assert.AreEqual(test, multiLineBasicJson); GeocodeService service = new GeocodeService(); GeocodeResult result = service.FindAddressCandidates(gcParams, this.Token); Assert.IsInstanceOfType(result, typeof(GeocodeResult)); Assert.IsNotNull(result.candidates, "Candidates should not be null."); Assert.IsNotNull(result.spatialReference, "Spatial Reference should not be null."); }
private async void MyMapView_GeoViewTapped(object sender, Esri.ArcGISRuntime.Xamarin.Forms.GeoViewInputEventArgs e) { try { // Clear existing callout and graphics. MyMapView.DismissCallout(); MyMapView.GraphicsOverlays[0].Graphics.Clear(); // Add a graphic for the tapped point. Graphic pinGraphic = await GraphicForPoint(e.Location); MyMapView.GraphicsOverlays[0].Graphics.Add(pinGraphic); // Reverse geocode to get addresses. ReverseGeocodeParameters parameters = new ReverseGeocodeParameters(); parameters.ResultAttributeNames.Add("*"); parameters.MaxResults = 1; IReadOnlyList <GeocodeResult> addresses = await _geocoder.ReverseGeocodeAsync(e.Location, parameters); // Skip if there are no results. if (!addresses.Any()) { await Application.Current.MainPage.DisplayAlert("No results", "No results found.", "OK"); return; } // Get the first result. GeocodeResult address = addresses.First(); // Use the address as the callout title. string calloutTitle = address.Attributes["Street"].ToString(); string calloutDetail = address.Attributes["City"] + ", " + address.Attributes["State"] + " " + address.Attributes["ZIP"]; // Define the callout. CalloutDefinition calloutBody = new CalloutDefinition(calloutTitle, calloutDetail); // Show the callout on the map at the tapped location. MyMapView.ShowCalloutForGeoElement(pinGraphic, e.Position, calloutBody); } catch (Exception ex) { await Application.Current.MainPage.DisplayAlert("Error", ex.ToString(), "OK"); } }
public async Task <WeatherModel> GetWeatherAsync(string city) { var model = new WeatherModel() { City = city }; GeocodeResult geocodeResult = null; try { geocodeResult = await GetGeoCodeByCityNameAsync(city); if (geocodeResult.ErrorOccured) { model.ErrorMessage = $"Could not find Coordinates for City: {city} (Try: { geocodeResult.ValidCities })"; } } catch (Exception) { model.ErrorMessage = "Failed to Fetch Geocode for specified City: " + city; } var geocode = geocodeResult.Geocode; if (!geocodeResult.ErrorOccured && geocode != null) { try { var weatherModel = await GetWeatherDataAsync(new Coordinate() { Longitude = geocode.longitude, Latitude = geocode.latitude }); model.Temperature = weatherModel.Temperature; model.ValidTime = weatherModel.ValidTime; } catch (Exception) { model.ErrorMessage = "Failed to Fetch Weather for specified City: " + city; } } return(model); }
private async Task <MapPoint> GeocodeArtistPlacename(string placeName) { MapPoint matchedPoint = null; LocatorTask locatorTask = new LocatorTask(new System.Uri(_locatorUrl)); GeocodeParameters p = new GeocodeParameters { MaxResults = 1, MinScore = 85 }; IReadOnlyList <GeocodeResult> placeMatches = await locatorTask.GeocodeAsync(placeName, p); if (placeMatches.Count > 0) { GeocodeResult place = placeMatches.FirstOrDefault(); matchedPoint = place.DisplayLocation; } return(matchedPoint); }
private async void MyMapView_GeoViewTapped(object sender, GeoViewInputEventArgs e) { try { // Clear the existing graphics & callouts. MyMapView.DismissCallout(); MyMapView.GraphicsOverlays[0].Graphics.Clear(); // Add a graphic for the tapped point. Graphic pinGraphic = await GraphicForPoint(e.Location); MyMapView.GraphicsOverlays[0].Graphics.Add(pinGraphic); // Normalize the geometry - needed if the user crosses the international date line. MapPoint normalizedPoint = (MapPoint)GeometryEngine.NormalizeCentralMeridian(e.Location); // Reverse geocode to get addresses. IReadOnlyList <GeocodeResult> addresses = await _geocoder.ReverseGeocodeAsync(normalizedPoint); // Get the first result. GeocodeResult address = addresses.First(); // Use the city and region for the Callout Title. string calloutTitle = address.Attributes["Address"].ToString(); // Use the metro area for the Callout Detail. string calloutDetail = address.Attributes["City"] + " " + address.Attributes["Region"] + " " + address.Attributes["CountryCode"]; // Define the callout. CalloutDefinition calloutBody = new CalloutDefinition(calloutTitle, calloutDetail); // Show the callout on the map at the tapped location. MyMapView.ShowCalloutForGeoElement(pinGraphic, e.Position, calloutBody); } catch (Exception ex) { Debug.WriteLine(ex); await new MessageDialog("No results found.", "No results").ShowAsync(); } }
internal RoutingState(GeocodeResult[] resultArray, int index) { results = resultArray; locationNumber = index; }
private Waypoint GeocodeResultToWaypoint(GeocodeResult result) { Waypoint waypoint = new Waypoint(); waypoint.Description = result.DisplayName; waypoint.Location = new Location(); waypoint.Location.Latitude = result.Locations[0].Latitude; waypoint.Location.Longitude = result.Locations[0].Longitude; return waypoint; }
void geocodeClient_GeocodeCompleted(object sender, GeocodeCompletedEventArgs e) { RoutingState state = e.UserState as RoutingState; GeocodeResult result = null; string outString; try { if (e.Result.ResponseSummary.StatusCode != GeocodeService.ResponseStatusCode.Success) { outString = "error geocoding ... status <" + e.Result.ResponseSummary.StatusCode.ToString() + ">"; } else if (0 == e.Result.Results.Count) { outString = "No result"; } else { // Only report on first result. result = e.Result.Results[0]; outString = result.DisplayName; } } catch (Exception) { outString = "Exception raised"; } // Update UI with geocode result. if (null != state.output) { state.output.Text = outString; } if (null == result) { result = new GeocodeResult(); } // Update state object ... when all the results are set, call route. bool doneGeocoding; lock (lockObject) { state.results[state.locationNumber] = result; doneGeocoding = state.GeocodesComplete; } if (doneGeocoding && state.GeocodesSuccessful) { ////Clear any existing routes //ClearRoute(); ////Calculate the route CalculateRoute(state.results); } }
private void EndingPointReceived(Mobica.GeocodeService.GeocodeResult coordinates) { try { //MessageBox.Show("Current location:" + curentLocation.Latitude + " " + curentLocation.Longitude); endPoint = coordinates; System.Device.Location.GeoCoordinate curentLocation = GPS.currentCoordinate; GeocodeResult currentPoint = new GeocodeResult(); { currentPoint.Locations = new System.Collections.ObjectModel.ObservableCollection<Mobica.GeocodeService.GeocodeLocation>(); currentPoint.Locations.Add(new GeocodeService.GeocodeLocation()); currentPoint.Locations[0].Latitude = curentLocation.Latitude; currentPoint.Locations[0].Longitude = curentLocation.Longitude; currentPoint.DisplayName = "You are here"; } //MessageBox.Show("I've got it!" + endPoint.Locations[0].Latitude + " " + endPoint.Locations[0].Longitude); TravelMode tm = TravelMode.Driving; if (_sets.GetValue("RouteMode") == "Walking mode") tm = TravelMode.Walking; bmh.CalculateRoute(map1, new GeocodeResult[] { currentPoint, endPoint }, RutedMapReceived, tm); } catch (NullReferenceException e) { MessageBox.Show("Position in GPS does not exist: " + e.Message); } }
public void CalculateAsync() { if (from_address == true) { // Geocode locations in parallel. var results = new GeocodeResult[2]; // To location. var state1 = new RoutingState(results, 1, _to); GeocodeAddress(_to, state1); // From location. var state0 = new RoutingState(results, 0, _from); GeocodeAddress(_from, state0); } }
/// <summary> /// Calculates a route, based on geocode resuls. /// </summary> private void CalculateRoute(GeocodeResult[] locations=null) { // Preparing a request for route calculation. var request = new RouteRequest() { Culture = CultureInfo.CurrentUICulture.Name, Waypoints = new ObservableCollection<Waypoint>(), // Don't raise exceptions. ExecutionOptions = new UsingBingMaps.Bing.Route.ExecutionOptions() { SuppressFaults = true }, // Only accept results with high confidence. Options = new RouteOptions() { RoutePathType = RoutePathType.Points } }; if (from_address == false) { Waypoint w_to = new Waypoint(); Waypoint w_from = new Waypoint(); w_to.Location = x_to; w_from.Location = x_from; request.Waypoints.Add(w_from); request.Waypoints.Add(w_to); } else { foreach (var result in locations) { request.Waypoints.Add(GeocodeResultToWaypoint(result)); } } // Get credentials and only then place an async call on the route service. _credentialsProvider.GetCredentials(credentials => { // Pass in credentials for web services call. // Replace with your own Credentials. request.Credentials = credentials; // Make asynchronous call to fetch the data. _routeClient.CalculateRouteAsync(request); }); }
//desc - pozwala ustawic wlasny opis waypointa private Waypoint GeocodeToWaypoint(GeocodeResult result, String desc = "") { RouteService.Waypoint waypoint = new RouteService.Waypoint(); try { if (String.IsNullOrEmpty(desc)) waypoint.Description = result.DisplayName; else waypoint.Description = desc; waypoint.Location = new Microsoft.Phone.Controls.Maps.Platform.Location(); waypoint.Location.Latitude = result.Locations[0].Latitude; waypoint.Location.Longitude = result.Locations[0].Longitude; } catch { MessageBox.Show("Waypoint does not exist"); } return waypoint; }
protected void Find_Address(Location location) { var geocoding = maps.ServiceHelper.GetGeocodeService(); geocoding.ReverseGeocodeCompleted += (sender, e) => { var correlated = e.UserState as Location; GeocodeResult.Clear(); GeocodeResult.AddRange(e.Result.Results); SelectedResult = GeocodeResult.FirstOrDefault(); }; geocoding.ReverseGeocodeAsync(new maps.GeocodeService.ReverseGeocodeRequest { Credentials = new Microsoft.Maps.MapControl.Credentials() { Token = maps.ServiceHelper.GeocodeServiceCredentials }, Culture = System.Threading.Thread.CurrentThread.CurrentUICulture.ToString(), Location = location }, location); }
protected void Search() { if(string.IsNullOrEmpty(Search_Address)) return; var geocoding = maps.ServiceHelper.GetGeocodeService(); geocoding.GeocodeCompleted += (sender, e) => { if (e.Error != null) return; GeocodeResult.Clear(); foreach (var item in e.Result.Results) GeocodeResult.Add(item); if (e.Result.Results.Count == 1) SelectedResult = e.Result.Results.First(); HasResults = GeocodeResult.Any(); }; geocoding.GeocodeAsync(new maps.GeocodeService.GeocodeRequest { Credentials = new Microsoft.Maps.MapControl.Credentials() { Token = maps.ServiceHelper.GeocodeServiceCredentials }, Culture = System.Threading.Thread.CurrentThread.CurrentUICulture.ToString(), Query = Search_Address }); }
protected void Select_Result(GeocodeResult result) { if (result == null) { Resolved_Address = null; Location = null; return; } Resolved_Address = result.Address; //! piu di una? Location = result.Locations.FirstOrDefault(); }
protected void Verify_Address_For_Location() { var geocoding = maps.ServiceHelper.GetGeocodeService(); geocoding.ReverseGeocodeCompleted += (sender, e) => { SelectedResult = e.Result.Results.SingleOrDefault(); }; geocoding.ReverseGeocodeAsync(new maps.GeocodeService.ReverseGeocodeRequest { Credentials = new Microsoft.Maps.MapControl.Credentials() { Token = maps.ServiceHelper.GeocodeServiceCredentials }, Location = Location }); }
internal RoutingState(GeocodeResult[] resultArray, int index, string tb) { Results = resultArray; LocationNumber = index; Output = tb; }
public void GetRoute(string FromOutput, string ToOutput) { // Geocode locations in parallel. GeocodeResult[] results = new GeocodeResult[2]; // From location. RoutingState state0 = new RoutingState(results, 0); GeocodeAddress(FromOutput, state0); // To location. RoutingState state1 = new RoutingState(results, 1); GeocodeAddress(ToOutput, state1); }
private Waypoint GeocodeResultToWaypoint(GeocodeResult result) { return new Waypoint() { Description = result.DisplayName, Location = new Location() { Latitude = result.Locations[0].Latitude, Longitude = result.Locations[0].Longitude } }; }
private void CalculateRoute(GeocodeResult[] locations) { RouteRequest request = new RouteRequest(); request.Waypoints = new ObservableCollection<Waypoint>(); foreach (GeocodeResult result in locations) { request.Waypoints.Add(GeocodeResultToWaypoint(result)); } // Don't raise exceptions. request.ExecutionOptions = new RouteService.ExecutionOptions(); request.ExecutionOptions.SuppressFaults = true; // Only accept results with high confidence. request.Options = new RouteOptions(); request.Options.RoutePathType = RoutePathType.Points; ((ClientTokenCredentialsProvider)App.Current.Resources["MyCredentials"]).GetCredentials( (Credentials credentials) => { //Pass in credentials for web services call. //Replace with your own Credentials. request.Credentials = credentials; // Make asynchronous call to fetch the data ... pass state object. RouteClient.CalculateRouteAsync(request); }); }
private void AddLocationPin(GeocodeResult result) { var point = new Point(result.Locations[0].Longitude, result.Locations[0].Latitude); if (resultsShapeLayer == null) { resultsShapeLayer = new GeometryLayer(MapInstance) { ID = "RESULTSLAYER" }; Style style = (Application.Current.Resources["PushPinArrowStyle"]) as Style; resultsShapeLayer.ItemsStyle = style; MapInstance.Layers.Add(resultsShapeLayer); } else { resultsShapeLayer.Clear(); } MapInstance.SetViewCenter(point, 12); //Add an arrow pin whose another point is an anchor of 0.5, 1.0; PointBase arrowPin = new PointBase { Point = point}; resultsShapeLayer.Add(arrowPin); }