public async Task<RouteResult> GetRoute(IEnumerable<MapPoint> stops, CancellationToken cancellationToken) { if (stops == null) throw new ArgumentNullException("stops"); List<Graphic> stopList = new List<Graphic>(); foreach (var stop in stops) { stopList.Add(new Graphic(stop)); } if (stopList.Count < 2) throw new ArgumentException("Not enough stops"); //determine which route service to use. Long distance routes should use the long-route service Polyline line = new Polyline() { SpatialReference = SpatialReferences.Wgs84 }; line.Paths.AddPart(stops.Select(m => m.Coordinate)); var length = GeometryEngine.GeodesicLength(line); string svc = routeService; if (length > 200000) svc = longRouteService; //Calculate route RouteTask task = new OnlineRouteTask(new Uri(svc)) { HttpMessageHandler = messageHandler }; var parameters = await task.GetDefaultParametersAsync().ConfigureAwait(false); parameters.Stops = new Esri.ArcGISRuntime.Tasks.NetworkAnalyst.FeaturesAsFeature(stopList); parameters.ReturnStops = true; parameters.OutputLines = OutputLine.TrueShapeWithMeasure; parameters.OutSpatialReference = SpatialReferences.Wgs84; parameters.DirectionsLengthUnit = LinearUnits.Meters; parameters.UseTimeWindows = false; parameters.RestrictionAttributeNames = new List<string>(new string[] { "OneWay " }); return await task.SolveAsync(parameters, cancellationToken); }
private async void DrawRoute(params Graphic[] graphics) { try { var routeTask = new OnlineRouteTask(new Uri("http://route.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World")); var routeParams = await routeTask.GetDefaultParametersAsync(); routeParams.OutSpatialReference = mapView.SpatialReference; routeParams.DirectionsLengthUnit = LinearUnits.Kilometers; routeParams.ReturnDirections = true; routeParams.SetStops(graphics); var routeResult = await routeTask.SolveAsync(routeParams); if (routeResult == null || routeResult.Routes == null || routeResult.Routes.Count == 0) { throw new Exception("Невозможно расчитать маршрут"); } var routeGraphic = new Graphic(routeResult.Routes[0].RouteFeature.Geometry, new SimpleLineSymbol { Color = Color.FromRgb(0, 0, 0), Style = SimpleLineStyle.Dash, Width = 2 }); ((GraphicsLayer)mapView.Map.Layers["Graphics"]).Graphics.Add(routeGraphic); await mapView.SetViewAsync(routeGraphic.Geometry.Extent); } catch (Exception e) { System.Diagnostics.Debug.Write(e.ToString()); } }
private async void MenuFlyoutGotoButton_Click(object sender, RoutedEventArgs e) { try { panelResults.Visibility = Visibility.Visible; progress.Visibility = Visibility.Visible; RouteParameters routeParams = await _routeTask.GetDefaultParametersAsync(); routeParams.OutSpatialReference = MyMapView.SpatialReference; routeParams.ReturnDirections = true; routeParams.DirectionsLengthUnit = LinearUnits.Kilometers; routeParams.DirectionsLanguage = new CultureInfo("es"); // CultureInfo.CurrentCulture; routeParams.SetStops(_stopsOverlay.Graphics); var routeResult = await _routeTask.SolveAsync(routeParams); if (routeResult == null || routeResult.Routes == null || routeResult.Routes.Count() == 0) { throw new Exception("No se pude calcular la ruta"); } var route = routeResult.Routes.First(); _routesOverlay.Graphics.Add(new Graphic(route.RouteFeature.Geometry)); _directionsOverlay.GraphicsSource = route.RouteDirections.Select(rd => GraphicFromRouteDirection(rd)); var totalTime = route.RouteDirections.Select(rd => rd.Time).Aggregate(TimeSpan.Zero, (p, v) => p.Add(v)); var totalLength = route.RouteDirections.Select(rd => rd.GetLength(LinearUnits.Kilometers)).Sum(); txtRouteTotals.Text = string.Format("Tiempo: {0:h':'mm':'ss} / Distancia: {1:0.00} km", totalTime, totalLength); await MyMapView.SetViewAsync(route.RouteFeature.Geometry.Extent.Expand(1.80)); } catch (AggregateException ex) { var message = ex.Message; var innermostExceptions = ex.Flatten().InnerExceptions; if (innermostExceptions != null && innermostExceptions.Count > 0) { message = innermostExceptions[0].Message; } var _x = new MessageDialog(message, "Error").ShowAsync(); } catch (Exception ex) { var _x = new MessageDialog(ex.Message, "Error").ShowAsync(); } finally { progress.Visibility = Visibility.Collapsed; if (_directionsOverlay.Graphics.Count() > 0) { panelResults.Visibility = Visibility.Visible; } } }
private async void mapView1_Tapped(object sender, Esri.ArcGISRuntime.Controls.MapViewInputEventArgs e) { var mp = e.Location; Graphic stop = new Graphic() { Geometry = mp }; var stopsGraphicsLayer = mapView1.Map.Layers["MyStopsGraphicsLayer"] as GraphicsLayer; stopsGraphicsLayer.Graphics.Add(stop); if (stopsGraphicsLayer.Graphics.Count > 1) { try { var routeTask = new OnlineRouteTask( new Uri("http://54.187.22.10:6080/arcgis/rest/services/RuteoBogota/NAServer/Route")); var routeParams = await routeTask.GetDefaultParametersAsync(); routeParams.SetStops(stopsGraphicsLayer.Graphics); routeParams.UseTimeWindows = false; routeParams.OutSpatialReference = mapView1.SpatialReference; routeParams.DirectionsLengthUnit = LinearUnits.Miles; routeParams.DirectionsLanguage = new CultureInfo("es-CO"); // CultureInfo.CurrentCulture; var result = await routeTask.SolveAsync(routeParams); if (result != null) { if (result.Routes != null && result.Routes.Count > 0) { var firstRoute = result.Routes.FirstOrDefault(); var direction = firstRoute.RouteDirections.FirstOrDefault(); if (direction != null) { int totalMins = 0; foreach (RouteDirection dir in firstRoute.RouteDirections) { totalMins = totalMins + dir.Time.Minutes; } await new MessageDialog(string.Format("{0:N2} minutos", totalMins)).ShowAsync(); } var routeLayer = mapView1.Map.Layers["MyRouteGraphicsLayer"] as GraphicsLayer; routeLayer.Graphics.Add(firstRoute.RouteFeature as Graphic); } } } catch (Exception ex) { var _x = new MessageDialog(ex.Message, "Error").ShowAsync(); } } }
private async void mapView1_Tapped(object sender, Esri.ArcGISRuntime.Controls.MapViewInputEventArgs e) { var mp = e.Location; Graphic stop = new Graphic() { Geometry = mp }; var stopsGraphicsLayer = mapView1.Map.Layers["MyStopsGraphicsLayer"] as GraphicsLayer; stopsGraphicsLayer.Graphics.Add(stop); if (stopsGraphicsLayer.Graphics.Count > 1) { try { var routeTask = new OnlineRouteTask(new Uri("http://tasks.arcgisonline.com/ArcGIS/rest/services/NetworkAnalysis/ESRI_Route_NA/NAServer/Route")); var routeParams = await routeTask.GetDefaultParametersAsync(); FeaturesAsFeature stopsFeatures = new FeaturesAsFeature(); stopsFeatures.Features = stopsGraphicsLayer.Graphics; routeParams.Stops = stopsFeatures; routeParams.UseTimeWindows = false; routeParams.OutSpatialReference = mapView1.SpatialReference; routeParams.DirectionsLengthUnit = LinearUnits.Miles; var result = await routeTask.SolveAsync(routeParams); if (result != null) { if (result.Routes != null && result.Routes.Count > 0) { var firstRoute = result.Routes.FirstOrDefault(); var direction = firstRoute.RouteDirections.FirstOrDefault(); if (direction != null) { int totalMins = 0; foreach (RouteDirection dir in firstRoute.RouteDirections) { totalMins = totalMins + dir.Time.Minutes; } await new MessageDialog(string.Format("{0:N2} minutes", totalMins)).ShowAsync(); } var routeLayer = mapView1.Map.Layers["MyRouteGraphicsLayer"] as GraphicsLayer; routeLayer.Graphics.Add(firstRoute.RouteGraphic); } } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } } }
private async void mapView1_Tapped(object sender, Esri.ArcGISRuntime.Controls.MapViewInputEventArgs e) { var mp = e.Location; Graphic stop = new Graphic() { Geometry = mp }; var stopsGraphicsLayer = mapView1.Map.Layers["MyStopsGraphicsLayer"] as GraphicsLayer; stopsGraphicsLayer.Graphics.Add(stop); if (stopsGraphicsLayer.Graphics.Count > 1) { try { var routeTask = new OnlineRouteTask(new Uri("http://tasks.arcgisonline.com/ArcGIS/rest/services/NetworkAnalysis/ESRI_Route_NA/NAServer/Route")); var routeParams = await routeTask.GetDefaultParametersAsync(); FeaturesAsFeature stopsFeatures = new FeaturesAsFeature(); stopsFeatures.Features = stopsGraphicsLayer.Graphics; routeParams.Stops = stopsFeatures; routeParams.UseTimeWindows = false; routeParams.OutSpatialReference = mapView1.SpatialReference; routeParams.DirectionsLengthUnit = LinearUnits.Miles; var result = await routeTask.SolveAsync(routeParams); if (result != null) { if (result.Routes != null && result.Routes.Count > 0) { var firstRoute = result.Routes.FirstOrDefault(); var direction = firstRoute.RouteDirections.FirstOrDefault(); if (direction != null) { int totalMins = 0; foreach (RouteDirection dir in firstRoute.RouteDirections) totalMins = totalMins + dir.Time.Minutes; await new MessageDialog(string.Format("{0:N2} minutes", totalMins)).ShowAsync(); } var routeLayer = mapView1.Map.Layers["MyRouteGraphicsLayer"] as GraphicsLayer; routeLayer.Graphics.Add(firstRoute.RouteGraphic); } } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } } }
public async Task <RouteResult> GetRoute(IEnumerable <MapPoint> stops, CancellationToken cancellationToken) { if (stops == null) { throw new ArgumentNullException("stops"); } List <Graphic> stopList = new List <Graphic>(); foreach (var stop in stops) { stopList.Add(new Graphic(stop)); } if (stopList.Count < 2) { throw new ArgumentException("Not enough stops"); } //determine which route service to use. Long distance routes should use the long-route service Polyline line = new Polyline() { SpatialReference = SpatialReferences.Wgs84 }; line.Paths.AddPart(stops.Select(m => m.Coordinate)); var length = GeometryEngine.GeodesicLength(line); string svc = routeService; if (length > 200000) { svc = longRouteService; } //Calculate route RouteTask task = new OnlineRouteTask(new Uri(svc)) { HttpMessageHandler = messageHandler }; var parameters = await task.GetDefaultParametersAsync().ConfigureAwait(false); parameters.Stops = new Esri.ArcGISRuntime.Tasks.NetworkAnalyst.FeaturesAsFeature(stopList); parameters.ReturnStops = true; parameters.OutputLines = OutputLine.TrueShapeWithMeasure; parameters.OutSpatialReference = SpatialReferences.Wgs84; parameters.DirectionsLengthUnit = LinearUnits.Meters; parameters.UseTimeWindows = false; parameters.RestrictionAttributeNames = new List <string>(new string[] { "OneWay " }); return(await task.SolveAsync(parameters, cancellationToken)); }
private async void MyMapView_Tapped(object sender, Esri.ArcGISRuntime.Controls.MapViewInputEventArgs e) { _routeGraphicsOverlay = MyMapView.GraphicsOverlays["RouteGraphicsOverlay"]; _stopsGraphicsOverlay = MyMapView.GraphicsOverlays["StopsGraphicsOverlay"]; var graphicIdx = _stopsGraphicsOverlay.Graphics.Count + 1; _stopsGraphicsOverlay.Graphics.Add(CreateStopGraphic(e.Location, graphicIdx)); if (_stopsGraphicsOverlay.Graphics.Count > 1) { try { progress.Visibility = Visibility.Visible; var routeTask = new OnlineRouteTask( new Uri("http://sampleserver6.arcgisonline.com/arcgis/rest/services/NetworkAnalysis/SanDiego/NAServer/Route")); var routeParams = await routeTask.GetDefaultParametersAsync(); routeParams.SetStops(_stopsGraphicsOverlay.Graphics); routeParams.UseTimeWindows = false; routeParams.OutSpatialReference = MyMapView.SpatialReference; routeParams.DirectionsLanguage = new CultureInfo("en-Us"); // CultureInfo.CurrentCulture; var result = await routeTask.SolveAsync(routeParams); if (result.Routes.Count > 0) { _routeGraphicsOverlay.Graphics.Clear(); var route = result.Routes.First().RouteFeature; _routeGraphicsOverlay.Graphics.Add(new Graphic(route.Geometry)); var meters = GeometryEngine.GeodesicLength(route.Geometry, GeodeticCurveType.Geodesic); txtDistance.Text = string.Format("{0:0.00} miles", LinearUnits.Miles.ConvertFromMeters(meters)); panelRouteInfo.Visibility = Visibility.Visible; } } catch (Exception ex) { var _x = new MessageDialog(ex.Message, "Sample Error").ShowAsync(); } finally { progress.Visibility = Visibility.Collapsed; } } }
public async Task SolveRoute() { if (_stopGraphicsOverlay.Graphics.Count < 2) { return; } try { progress.Visibility = Visibility.Visible; _routeParams.SetStops(_stopGraphicsOverlay.Graphics); _routeParams.SetPointBarriers(_barrierGraphicsOverlay.Graphics); _routeParams.OutSpatialReference = MyMapView.SpatialReference; RouteResult routeResult = await _routeTask.SolveAsync(_routeParams); if (routeResult.Routes.Count > 0) { _routeGraphicsOverlay.Graphics.Clear(); var route = routeResult.Routes.First().RouteFeature; _routeGraphicsOverlay.Graphics.Add(new Graphic(route.Geometry)); } } catch (AggregateException ex) { var innermostExceptions = ex.Flatten().InnerExceptions; if (innermostExceptions != null && innermostExceptions.Count > 0) { MessageBox.Show(innermostExceptions[0].Message); } else { MessageBox.Show(ex.Message); } } catch (System.Exception ex) { MessageBox.Show("Error: " + ex.Message); } finally { progress.Visibility = Visibility.Collapsed; } }
private async void OnSolveRouteClicked(object sender, RoutedEventArgs e) { var stopsLayer = mapView1.Map.Layers["MyStopsGraphicsLayer"] as GraphicsLayer; var barriersLayer = mapView1.Map.Layers["MyBarriersGraphicsLayer"] as GraphicsLayer; if (stopsLayer.Graphics.Count > 1) { try { OnlineRouteTask routeTask = new OnlineRouteTask(new Uri("http://tasks.arcgisonline.com/ArcGIS/rest/services/NetworkAnalysis/ESRI_Route_NA/NAServer/Route")); RouteParameters routeParams = await routeTask.GetDefaultParametersAsync(); FeaturesAsFeature featureAsFeature = new FeaturesAsFeature(); featureAsFeature.Features = stopsLayer.Graphics; routeParams.Stops = featureAsFeature; routeParams.UseTimeWindows = false; routeParams.OutSpatialReference = mapView1.SpatialReference; FeaturesAsFeature barrierFeatures = new FeaturesAsFeature(); barrierFeatures.Features = barriersLayer.Graphics; routeParams.PointBarriers = barrierFeatures; routeParams.OutputGeometryPrecision = 1; //routeParams.OutputGeometryPrecisionUnit = LinearUnits.Miles; routeParams.DirectionsLengthUnit = LinearUnits.Miles; var result = await routeTask.SolveAsync(routeParams); if (result != null) { GraphicsLayer routeLayer = mapView1.Map.Layers["MyRouteGraphicsLayer"] as GraphicsLayer; routeLayer.Graphics.Clear(); foreach (var route in result.Routes) { routeLayer.Graphics.Add(route.RouteGraphic); } } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } } }
private async void OnSolveRouteClicked(object sender, RoutedEventArgs e) { var stopsLayer = mapView1.Map.Layers["MyStopsGraphicsLayer"] as GraphicsLayer; var barriersLayer = mapView1.Map.Layers["MyBarriersGraphicsLayer"] as GraphicsLayer; if (stopsLayer.Graphics.Count > 1) { try { OnlineRouteTask routeTask = new OnlineRouteTask(new Uri("http://tasks.arcgisonline.com/ArcGIS/rest/services/NetworkAnalysis/ESRI_Route_NA/NAServer/Route")); RouteParameters routeParams = await routeTask.GetDefaultParametersAsync(); FeaturesAsFeature featureAsFeature = new FeaturesAsFeature(); featureAsFeature.Features = stopsLayer.Graphics; routeParams.Stops = featureAsFeature; routeParams.UseTimeWindows = false; routeParams.OutSpatialReference = mapView1.SpatialReference; FeaturesAsFeature barrierFeatures = new FeaturesAsFeature(); barrierFeatures.Features = barriersLayer.Graphics; routeParams.PointBarriers = barrierFeatures; routeParams.OutputGeometryPrecision = 1; //routeParams.OutputGeometryPrecisionUnit = LinearUnits.Miles; routeParams.DirectionsLengthUnit = LinearUnits.Miles; var result = await routeTask.SolveAsync(routeParams); if (result != null) { GraphicsLayer routeLayer = mapView1.Map.Layers["MyRouteGraphicsLayer"] as GraphicsLayer; routeLayer.Graphics.Clear(); foreach (var route in result.Routes) routeLayer.Graphics.Add(route.RouteGraphic); } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } } }
private async void OnSolveRouteClicked(object sender, RoutedEventArgs e) { var stopsLayer = mapView1.Map.Layers["MyStopsGraphicsLayer"] as GraphicsLayer; var barriersLayer = mapView1.Map.Layers["MyBarriersGraphicsLayer"] as GraphicsLayer; if (stopsLayer.Graphics.Count > 1) { try { OnlineRouteTask routeTask = new OnlineRouteTask (new Uri("http://sampleserver6.arcgisonline.com/arcgis/rest/services/NetworkAnalysis/SanDiego/NAServer/Route")); RouteParameters routeParams = await routeTask.GetDefaultParametersAsync(); routeParams.SetStops(stopsLayer.Graphics); routeParams.UseTimeWindows = false; routeParams.OutSpatialReference = mapView1.SpatialReference; routeParams.SetPointBarriers(barriersLayer.Graphics); routeParams.OutputGeometryPrecision = 1; routeParams.DirectionsLengthUnit = LinearUnits.Miles; routeParams.DirectionsLanguage = new CultureInfo("en-Us"); // CultureInfo.CurrentCulture; var result = await routeTask.SolveAsync(routeParams); if (result != null) { GraphicsLayer routeLayer = mapView1.Map.Layers["MyRouteGraphicsLayer"] as GraphicsLayer; routeLayer.Graphics.Clear(); foreach (var route in result.Routes) { routeLayer.Graphics.Add(route.RouteFeature as Graphic); } } } catch (Exception ex) { var _x = new MessageDialog(ex.Message, "Sample Error").ShowAsync(); } } }
private async void GetDirections_Click(object sender, RoutedEventArgs e) { //Reset DirectionsStackPanel.Children.Clear(); var _stops = new List<Graphic>(); var _locator = new OnlineLocatorTask(new Uri("http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer"), ""); var routeLayer = mapView1.Map.Layers["MyRouteGraphicsLayer"] as GraphicsLayer; routeLayer.Graphics.Clear(); try { var fields = new List<string> { "Loc_name" }; //Geocode from address var fromLocation = await _locator.GeocodeAsync(ParseAddress(FromTextBox.Text), fields, CancellationToken.None); if (fromLocation != null && fromLocation.Count > 0) { var result = fromLocation.FirstOrDefault(); Graphic graphicLocation = new Graphic() { Geometry = result.Location, Symbol = LayoutRoot.Resources["FromSymbol"] as Esri.ArcGISRuntime.Symbology.Symbol }; graphicLocation.Attributes["address"] = result.Address; graphicLocation.Attributes["score"] = result.Score; _stops.Add(graphicLocation); routeLayer.Graphics.Add(graphicLocation); } //Geocode to address var toLocation = await _locator.GeocodeAsync(ParseAddress(ToTextBox.Text), fields, CancellationToken.None); if (toLocation != null && toLocation.Count > 0) { var result = toLocation.FirstOrDefault(); Graphic graphicLocation = new Graphic() { Geometry = result.Location, Symbol = LayoutRoot.Resources["ToSymbol"] as Esri.ArcGISRuntime.Symbology.Symbol }; graphicLocation.Attributes["address"] = result.Address; graphicLocation.Attributes["score"] = result.Score; _stops.Add(graphicLocation); routeLayer.Graphics.Add(graphicLocation); } var routeTask = new OnlineRouteTask(new Uri("http://tasks.arcgisonline.com/ArcGIS/rest/services/NetworkAnalysis/ESRI_Route_NA/NAServer/Route")); RouteParameters routeParams = await routeTask.GetDefaultParametersAsync(); routeParams.ReturnRoutes = true; routeParams.ReturnDirections = true; routeParams.DirectionsLengthUnit = LinearUnits.Miles; routeParams.UseTimeWindows = false; routeParams.OutSpatialReference = mapView1.SpatialReference; routeParams.Stops = new FeaturesAsFeature(routeLayer.Graphics); var routeTaskResult = await routeTask.SolveAsync(routeParams); _directionsFeatureSet = routeTaskResult.Routes.FirstOrDefault(); _directionsFeatureSet.RouteGraphic.Symbol = LayoutRoot.Resources["RouteSymbol"] as Esri.ArcGISRuntime.Symbology.Symbol; routeLayer.Graphics.Add(_directionsFeatureSet.RouteGraphic); var totalLength = _directionsFeatureSet.GetTotalLength(LinearUnits.Miles); var calculatedLength = _directionsFeatureSet.RouteDirections.Sum(x => x.GetLength(LinearUnits.Miles)); TotalDistanceTextBlock.Text = string.Format("Total Distance: {0:N3} miles", totalLength); TotalTimeTextBlock.Text = string.Format("Total Time: {0}", FormatTime(_directionsFeatureSet.TotalTime.TotalMinutes)); TitleTextBlock.Text = _directionsFeatureSet.RouteName; int i = 1; foreach (var item in _directionsFeatureSet.RouteDirections) { TextBlock textBlock = new TextBlock() { Text = string.Format("{0:00} - {1}", i, item.Text), Tag = item.Geometry, Margin = new Thickness(0, 15,0,0), FontSize = 20 }; textBlock.Tapped += TextBlock_Tapped; DirectionsStackPanel.Children.Add(textBlock); var secondarySP = new StackPanel() { Orientation = Orientation.Horizontal }; if (item.Time.TotalMinutes > 0) { var timeTb = new TextBlock { Text = string.Format("Time : {0:N2} minutes", item.Time.TotalMinutes), Margin= new Thickness(45,0,0,0) }; secondarySP.Children.Add(timeTb); var distTb = new TextBlock { Text = string.Format("Distance : {0:N2} miles", item.GetLength(LinearUnits.Miles)), Margin = new Thickness(25, 0, 0, 0) }; secondarySP.Children.Add(distTb); DirectionsStackPanel.Children.Add(secondarySP); } i++; } mapView1.SetView(_directionsFeatureSet.RouteGraphic.Geometry.Extent.Expand(1.2)); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } }
private async void SolveButton_Click(object sender, RoutedEventArgs e) { try { if (_stops.Count == 0) { return; } RouteParameters routeParams = await _onlineRouteTask.GetDefaultParametersAsync(); GenerateBarriers(); FeaturesAsFeature stopsFeatures = new FeaturesAsFeature(); stopsFeatures.Features = _stops; routeParams.Stops = stopsFeatures; if (_polylineBarriers.Count > 0) { FeaturesAsFeature polylineBarrierFeatures = new FeaturesAsFeature(); polylineBarrierFeatures.Features = _polylineBarriers; routeParams.PolylineBarriers = polylineBarrierFeatures; } if (_polygonBarriers.Count > 0) { FeaturesAsFeature polygonBarrierFeatures = new FeaturesAsFeature(); polygonBarrierFeatures.Features = _polygonBarriers; routeParams.PolygonBarriers = polygonBarrierFeatures; } List <AttributeParameterValue> aps = new List <AttributeParameterValue>(); AttributeParameterValue apv = GetAttributeParameterValue(AttributeParameter2.SelectionBoxItem.ToString().Trim()); if (apv != null) { aps.Add(apv); } //routeParams.AttributeParameterValues = aps; //routeParams.ReturnDirections = ReturnDirections2.IsChecked.HasValue ? ReturnDirections2.IsChecked.Value : false; routeParams.DirectionsLanguage = String.IsNullOrEmpty(DirectionsLanguage2.Text) ? new System.Globalization.CultureInfo("en-US") : new System.Globalization.CultureInfo(DirectionsLanguage2.Text); routeParams.DirectionsLengthUnit = GetDirectionsLengthUnits(DirectionsLengthUnits2.SelectionBoxItem.ToString().Trim()); routeParams.ReturnRoutes = ReturnRoutes2.IsChecked.HasValue ? ReturnRoutes2.IsChecked.Value : false; routeParams.ReturnStops = ReturnFacilities2.IsChecked.HasValue ? ReturnFacilities2.IsChecked.Value : false; routeParams.ReturnPointBarriers = ReturnBarriers2.IsChecked.HasValue ? ReturnBarriers2.IsChecked.Value : false; routeParams.ReturnPolygonBarriers = ReturnPolygonBarriers2.IsChecked.HasValue ? ReturnPolygonBarriers2.IsChecked.Value : false; routeParams.ReturnPolylineBarriers = ReturnPolylineBarriers2.IsChecked.HasValue ? ReturnPolylineBarriers2.IsChecked.Value : false; routeParams.OutputLines = GetOutputLines(OutputLines2.SelectionBoxItem.ToString().Trim()); routeParams.OutSpatialReference = string.IsNullOrEmpty(OutputSpatialReference2.Text) ? mapView1.SpatialReference : new SpatialReference(int.Parse(OutputSpatialReference2.Text)); //routeParams.AccumulateAttributeNames = AccumulateAttributeNames2.Text.Split(','); routeParams.ImpedanceAttributeName = ImpedanceAttributeName2.Text; routeParams.RestrictionAttributeNames = RestrictionAttributeNames2.Text.Split(','); routeParams.RestrictUTurns = GetRestrictUTurns(RestrictUTurns2.SelectionBoxItem.ToString().Trim()); routeParams.UseHierarchy = UseHierarchy2.IsChecked.HasValue ? UseHierarchy2.IsChecked.Value : false; routeParams.OutputGeometryPrecision = string.IsNullOrEmpty(OutputGeometryPrecision2.Text) ? 0 : double.Parse(OutputGeometryPrecision2.Text); routeParams.OutputGeometryPrecisionUnit = GetGeometryPrecisionUnits(OutputGeometryPrecisionUnits2.SelectionBoxItem.ToString().Trim()); RouteResult result = await _onlineRouteTask.SolveAsync(routeParams); _routeGraphicsLayer.Graphics.Clear(); foreach (Route route in result.Routes) { Graphic g = route.RouteGraphic; g.Symbol = LayoutRoot.Resources["RouteSymbol"] as SimpleLineSymbol; _routeGraphicsLayer.Graphics.Add(g); } } catch (Exception ex) { var dlg = new MessageDialog(ex.Message, "Solve Failed!"); var _ = dlg.ShowAsync(); } }
// Calculate the route private async void MyMapView_MapViewDoubleTapped(object sender, Esri.ArcGISRuntime.Controls.MapViewInputEventArgs e) { if (_stopsOverlay.Graphics.Count() < 2) { return; } try { e.Handled = true; panelResults.Visibility = Visibility.Collapsed; progress.Visibility = Visibility.Visible; RouteParameters routeParams = await _routeTask.GetDefaultParametersAsync(); routeParams.OutSpatialReference = MyMapView.SpatialReference; routeParams.ReturnDirections = true; routeParams.DirectionsLengthUnit = LinearUnits.Miles; routeParams.DirectionsLanguage = new CultureInfo("en-Us"); // CultureInfo.CurrentCulture; routeParams.SetStops(_stopsOverlay.Graphics); var routeResult = await _routeTask.SolveAsync(routeParams); if (routeResult == null || routeResult.Routes == null || routeResult.Routes.Count() == 0) { throw new Exception("No route could be calculated"); } var route = routeResult.Routes.First(); _routesOverlay.Graphics.Add(new Graphic(route.RouteFeature.Geometry)); _directionsOverlay.GraphicsSource = route.RouteDirections.Select(rd => GraphicFromRouteDirection(rd)); var totalTime = route.RouteDirections.Select(rd => rd.Time).Aggregate(TimeSpan.Zero, (p, v) => p.Add(v)); var totalLength = route.RouteDirections.Select(rd => rd.GetLength(LinearUnits.Miles)).Sum(); txtRouteTotals.Text = string.Format("Time: {0:h':'mm':'ss} / Length: {1:0.00} mi", totalTime, totalLength); await MyMapView.SetViewAsync(route.RouteFeature.Geometry.Extent.Expand(1.25)); } catch (AggregateException ex) { var message = ex.Message; var innermostExceptions = ex.Flatten().InnerExceptions; if (innermostExceptions != null && innermostExceptions.Count > 0) { message = innermostExceptions[0].Message; } var _x = new MessageDialog(message, "Sample Error").ShowAsync(); } catch (Exception ex) { var _x = new MessageDialog(ex.Message, "Sample Error").ShowAsync(); } finally { progress.Visibility = Visibility.Collapsed; if (_directionsOverlay.Graphics.Count() > 0) { panelResults.Visibility = Visibility.Visible; } } }
private async void GetDirectionsButton_Click(object sender, RoutedEventArgs e) { var from = await this.FindAddress(this.FromTextBox.Text); var to = await FindAddress(ToTextBox.Text); try { if (from == null) { throw new Exception("Unable to find a match for '" + this.FromTextBox.Text + "'."); } if (to == null) { throw new Exception("Unable to find a match for '" + this.ToTextBox.Text + "'."); } // get the RouteResults graphics layer; add the from/to graphics var routeGraphics = MyMap.Layers["RouteResults"] as GraphicsLayer; if (routeGraphics == null) { throw new Exception("A graphics layer named 'RouteResults' was not found in the map."); } // code here to show address locations on the map var fromMapPoint = GeometryEngine.Project(from.Geometry, new SpatialReference(102100)); var toMapPoint = GeometryEngine.Project(to.Geometry, new SpatialReference(102100)); var fromSym = new SimpleMarkerSymbol { Style = SimpleMarkerStyle.Circle, Size = 16, Color = Colors.Green }; var toSym = new SimpleMarkerSymbol { Style = SimpleMarkerStyle.Circle, Size = 16, Color = Colors.Red }; var fromMapGraphic = new Graphic { Geometry = fromMapPoint, Symbol = fromSym }; var toMapGraphic = new Graphic { Geometry = toMapPoint, Symbol = toSym }; routeGraphics.Graphics.Add(fromMapGraphic); routeGraphics.Graphics.Add(toMapGraphic); var uri = new Uri("http://tasks.arcgisonline.com/ArcGIS/rest/services/NetworkAnalysis/ESRI_Route_NA/NAServer/Route"); var routeTask = new OnlineRouteTask(uri); var routeParams = await routeTask.GetDefaultParametersAsync(); routeParams.OutSpatialReference = MyMapView.SpatialReference; routeParams.DirectionsLengthUnit = LinearUnits.Miles; routeParams.ReturnDirections = true; // add stop parameters var stopGraphics = new List<Graphic>(); stopGraphics.Add(from); stopGraphics.Add(to); routeParams.SetStops(stopGraphics); // save the route var routeResult = await routeTask.SolveAsync(routeParams); if(routeResult == null || routeResult.Routes == null || routeResult.Routes.Count == 0) { throw new Exception("Unable to solve the route."); } var firstRoute = routeResult.Routes[0]; var routeFeature = firstRoute.RouteFeature; var routeSym = new SimpleLineSymbol { Color = Colors.Navy, Style = SimpleLineStyle.Dash, Width = 2 }; var routeGraphic = new Graphic(routeFeature.Geometry, routeSym); routeGraphics.Graphics.Add(routeGraphic); await MyMapView.SetViewAsync(routeGraphic.Geometry.Extent); var directionsBuilder = new System.Text.StringBuilder(); var totalMiles = 0.0; var totalMinutes = 0.0; var step = 1; foreach (var d in firstRoute.RouteDirections) { // appends a step number followed by a tab followed by the directions, then a new line directionsBuilder.AppendFormat("{0} \t {1}", step.ToString(), d.Text + "\n"); step++; totalMiles += d.GetLength(LinearUnits.Miles); totalMinutes += d.Time.TotalMinutes; } // update the app UI this.RouteDistance.Text = totalMiles.ToString("0.00") + " miles"; this.RouteTime.Text = totalMinutes.ToString("0.00") + " minutes"; this.DirectionsTextBlock.Text = directionsBuilder.ToString(); } catch (Exception exp) { this.DirectionsTextBlock.Text = exp.Message; } }
private async Task <int> RunRouting() { try { _networkingToolView.ViewModel.PanelResultsVisibility = Visibility.Collapsed; _networkingToolView.ViewModel.ProgressVisibility = Visibility.Visible; RouteParameters routeParams = await _routeTask.GetDefaultParametersAsync(); routeParams.OutSpatialReference = _mapView.SpatialReference; routeParams.ReturnDirections = true; routeParams.DirectionsLengthUnit = LinearUnits.Miles; routeParams.DirectionsLanguage = new CultureInfo("en-Us"); // CultureInfo.CurrentCulture; routeParams.SetStops(_stopsOverlay.Graphics); var routeResult = await _routeTask.SolveAsync(routeParams); if (routeResult == null || routeResult.Routes == null || !routeResult.Routes.Any()) { throw new Exception("No route could be calculated"); } var route = routeResult.Routes.First(); _routesOverlay.Graphics.Add(new Graphic(route.RouteFeature.Geometry)); _directionsOverlay.GraphicsSource = route.RouteDirections.Select(rd => GraphicFromRouteDirection(rd)); _networkingToolView.ViewModel.Graphics = _directionsOverlay.Graphics; var totalTime = route.RouteDirections.Select(rd => rd.Time).Aggregate(TimeSpan.Zero, (p, v) => p.Add(v)); var totalLength = route.RouteDirections.Select(rd => rd.GetLength(LinearUnits.Miles)).Sum(); _networkingToolView.ViewModel.RouteTotals = string.Format("Time: {0:h':'mm':'ss} / Length: {1:0.00} mi", totalTime, totalLength); if (!route.RouteFeature.Geometry.IsEmpty) { await _mapView.SetViewAsync(route.RouteFeature.Geometry.Extent.Expand(1.25)); } } catch (AggregateException ex) { var innermostExceptions = ex.Flatten().InnerExceptions; if (innermostExceptions != null && innermostExceptions.Count > 0) { MessageBox.Show(innermostExceptions[0].Message, "Sample Error"); } else { MessageBox.Show(ex.Message, "Sample Error"); } Reset(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Sample Error"); Reset(); } finally { _networkingToolView.ViewModel.ProgressVisibility = Visibility.Collapsed; if (_directionsOverlay.Graphics.Any()) { _networkingToolView.ViewModel.PanelResultsVisibility = Visibility.Visible; } } return(0); }
private async void GetDirections_Click(object sender, RoutedEventArgs e) { //Reset DirectionsStackPanel.Children.Clear(); var _stops = new List <Graphic>(); var _locator = new OnlineLocatorTask(new Uri("http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer"), ""); var routeLayer = mapView1.Map.Layers["MyRouteGraphicsLayer"] as GraphicsLayer; routeLayer.Graphics.Clear(); try { var fields = new List <string> { "Loc_name" }; //Geocode from address var fromLocation = await _locator.GeocodeAsync(ParseAddress(FromTextBox.Text), fields, CancellationToken.None); if (fromLocation != null && fromLocation.Count > 0) { var result = fromLocation.FirstOrDefault(); Graphic graphicLocation = new Graphic() { Geometry = result.Location, Symbol = LayoutRoot.Resources["FromSymbol"] as Esri.ArcGISRuntime.Symbology.Symbol }; graphicLocation.Attributes["address"] = result.Address; graphicLocation.Attributes["score"] = result.Score; _stops.Add(graphicLocation); routeLayer.Graphics.Add(graphicLocation); } //Geocode to address var toLocation = await _locator.GeocodeAsync(ParseAddress(ToTextBox.Text), fields, CancellationToken.None); if (toLocation != null && toLocation.Count > 0) { var result = toLocation.FirstOrDefault(); Graphic graphicLocation = new Graphic() { Geometry = result.Location, Symbol = LayoutRoot.Resources["ToSymbol"] as Esri.ArcGISRuntime.Symbology.Symbol }; graphicLocation.Attributes["address"] = result.Address; graphicLocation.Attributes["score"] = result.Score; _stops.Add(graphicLocation); routeLayer.Graphics.Add(graphicLocation); } var routeTask = new OnlineRouteTask(new Uri("http://tasks.arcgisonline.com/ArcGIS/rest/services/NetworkAnalysis/ESRI_Route_NA/NAServer/Route")); RouteParameters routeParams = await routeTask.GetDefaultParametersAsync(); routeParams.ReturnRoutes = true; routeParams.ReturnDirections = true; routeParams.DirectionsLengthUnit = LinearUnits.Miles; routeParams.UseTimeWindows = false; routeParams.OutSpatialReference = mapView1.SpatialReference; routeParams.Stops = new FeaturesAsFeature(routeLayer.Graphics); var routeTaskResult = await routeTask.SolveAsync(routeParams); _directionsFeatureSet = routeTaskResult.Routes.FirstOrDefault(); _directionsFeatureSet.RouteGraphic.Symbol = LayoutRoot.Resources["RouteSymbol"] as Esri.ArcGISRuntime.Symbology.Symbol; routeLayer.Graphics.Add(_directionsFeatureSet.RouteGraphic); var totalLength = _directionsFeatureSet.GetTotalLength(LinearUnits.Miles); var calculatedLength = _directionsFeatureSet.RouteDirections.Sum(x => x.GetLength(LinearUnits.Miles)); TotalDistanceTextBlock.Text = string.Format("Total Distance: {0:N3} miles", totalLength); TotalTimeTextBlock.Text = string.Format("Total Time: {0}", FormatTime(_directionsFeatureSet.TotalTime.TotalMinutes)); TitleTextBlock.Text = _directionsFeatureSet.RouteName; int i = 1; foreach (var item in _directionsFeatureSet.RouteDirections) { TextBlock textBlock = new TextBlock() { Text = string.Format("{0:00} - {1}", i, item.Text), Tag = item.Geometry, Margin = new Thickness(0, 15, 0, 0), FontSize = 20 }; textBlock.Tapped += TextBlock_Tapped; DirectionsStackPanel.Children.Add(textBlock); var secondarySP = new StackPanel() { Orientation = Orientation.Horizontal }; if (item.Time.TotalMinutes > 0) { var timeTb = new TextBlock { Text = string.Format("Time : {0:N2} minutes", item.Time.TotalMinutes), Margin = new Thickness(45, 0, 0, 0) }; secondarySP.Children.Add(timeTb); var distTb = new TextBlock { Text = string.Format("Distance : {0:N2} miles", item.GetLength(LinearUnits.Miles)), Margin = new Thickness(25, 0, 0, 0) }; secondarySP.Children.Add(distTb); DirectionsStackPanel.Children.Add(secondarySP); } i++; } mapView1.SetView(_directionsFeatureSet.RouteGraphic.Geometry.Extent.Expand(1.2)); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } }