void locator_FindCompleted(object sender, LocatorFindEventArgs e) { GraphicsLayer graphicsLayer = (MyMap.Layers["MyRouteGraphicsLayer"] as GraphicsLayer); if (e.Result != null) { LocatorFindResult findResult = e.Result; Graphic graphicLocation = findResult.Locations[0].Graphic; graphicLocation.Geometry.SpatialReference = MyMap.SpatialReference; graphicLocation.Attributes.Add("name", findResult.Locations[0].Name); _stops.Add(graphicLocation); if ((string)e.UserState == "from") { graphicLocation.Symbol = LayoutRoot.Resources["FromSymbol"] as ESRI.ArcGIS.Client.Symbols.Symbol; //Geocode to address _locator.FindAsync(ParseSearchText(ToTextBox.Text), "to"); } else { graphicLocation.Symbol = LayoutRoot.Resources["ToSymbol"] as ESRI.ArcGIS.Client.Symbols.Symbol; //Get route between from and to _routeParams.OutSpatialReference = MyMap.SpatialReference; _routeTask.SolveAsync(_routeParams); } graphicsLayer.Graphics.Add(graphicLocation); } }
private void MyDrawObject_DrawComplete(object sender, ESRI.ArcGIS.Client.DrawEventArgs e) { GraphicsLayer stopsGraphicsLayer = MyMap.Layers["MyStopsGraphicsLayer"] as GraphicsLayer; Graphic stop = new Graphic() { Geometry = e.Geometry, Symbol = LayoutRoot.Resources["StopSymbol"] as ESRI.ArcGIS.Client.Symbols.Symbol }; stopsGraphicsLayer.Graphics.Add(stop); if (stopsGraphicsLayer.Graphics.Count > 1) { RouteTask routeTask = LayoutRoot.Resources["MyRouteTask"] as RouteTask; if (routeTask.IsBusy) { routeTask.CancelAsync(); stopsGraphicsLayer.Graphics.RemoveAt(stopsGraphicsLayer.Graphics.Count - 1); } routeTask.SolveAsync(new RouteParameters() { Stops = stopsGraphicsLayer, UseTimeWindows = false, OutSpatialReference = MyMap.SpatialReference }); } }
void locator_AddressToLocationsCompleted(object sender, AddressToLocationsEventArgs e) { GraphicsLayer graphicsLayer = (MyMap.Layers["MyRouteGraphicsLayer"] as GraphicsLayer); if (e.Results.Count > 0) { AddressCandidate address = e.Results[0]; Graphic graphicLocation = new Graphic() { Geometry = address.Location }; graphicLocation.Attributes.Add("address", address.Address); graphicLocation.Attributes.Add("score", address.Score); _stops.Add(graphicLocation); if ((string)e.UserState == "from") { graphicLocation.Symbol = LayoutRoot.Resources["FromSymbol"] as ESRI.ArcGIS.Client.Symbols.Symbol; //Geocode to address _locator.AddressToLocationsAsync(ParseAddress(ToTextBox.Text), "to"); } else { graphicLocation.Symbol = LayoutRoot.Resources["ToSymbol"] as ESRI.ArcGIS.Client.Symbols.Symbol; //Get route between from and to _routeParams.OutSpatialReference = MyMap.SpatialReference; _routeTask.SolveAsync(_routeParams); } graphicsLayer.Graphics.Add(graphicLocation); } }
void myDrawObject_DrawComplete(object sender, DrawEventArgs e) { if (StopsRadioButton.IsChecked.Value) { Graphic stop = new Graphic() { Geometry = e.Geometry, Symbol = LayoutRoot.Resources["StopSymbol"] as ESRI.ArcGIS.Client.Symbols.Symbol }; stop.Attributes.Add("StopNumber", stopsLayer.Graphics.Count + 1); stopsLayer.Graphics.Add(stop); _stops.Add(stop); } else if (BarriersRadioButton.IsChecked.Value) { Graphic barrier = new Graphic() { Geometry = e.Geometry, Symbol = LayoutRoot.Resources["BarrierSymbol"] as ESRI.ArcGIS.Client.Symbols.Symbol }; barriersLayer.Graphics.Add(barrier); _barriers.Add(barrier); } if (_stops.Count > 1) { if (_routeTask.IsBusy) { _routeTask.CancelAsync(); } _routeParams.OutSpatialReference = MyMap.SpatialReference; _routeTask.SolveAsync(_routeParams); } }
void SolveRoute(MapPoint start, MapPoint end) { // The Esri World Network Analysis Services requires an ArcGIS Online Subscription. // In this sample use the North America only service on tasks.arcgisonline.com. var routeTask = new RouteTask("http://tasks.arcgisonline.com/ArcGIS/rest/services/NetworkAnalysis/ESRI_Route_NA/NAServer/Route"); // Create a new list of graphics to send to the route task. Note don't use the graphcis returned from find // as the attributes cause issues with the route finding. var stops = new List <Graphic>() { new Graphic() { Geometry = start }, new Graphic() { Geometry = end } }; var routeParams = new RouteParameters() { Stops = stops, UseTimeWindows = false, OutSpatialReference = MyMap.SpatialReference, ReturnDirections = false, IgnoreInvalidLocations = true }; routeTask.Failed += (s, e) => { MessageBox.Show("Route Task failed:" + e.Error); }; // Register an inline handler for the SolveCompleted event. routeTask.SolveCompleted += (s, e) => { // Add the returned route to the Map var myRoute = new Graphic() { Geometry = e.RouteResults[0].Route.Geometry, Symbol = new SimpleLineSymbol() { Width = 10, Color = new SolidColorBrush(Color.FromArgb(127, 0, 0, 255)) } }; // Add a MapTip decimal totalTime = (decimal)e.RouteResults[0].Route.Attributes["Total_Time"]; string tip = string.Format("{0} minutes", totalTime.ToString("#0.0")); myRoute.Attributes.Add("TIP", tip); MyRoutesGraphicsLayer.Graphics.Add(myRoute); }; // Call the SolveAsync method routeTask.SolveAsync(routeParams); }
private async Task <Graphic> GetRouteGraphicAsync(MapPoint startLocation, MapPoint endLocation) { // Wait until previous routing is completed before doing another if (_isRouting) { return(null); } _isRouting = true; RouteParameters routeParameters = await _routeTask.GetDefaultParametersAsync(); routeParameters.OutSpatialReference = MapViewService.SpatialReference; routeParameters.ReturnDirections = false; routeParameters.DirectionsLengthUnit = LinearUnits.Kilometers; // Add endpoints to for the route List <Graphic> graphicsStops = new List <Graphic>(); graphicsStops.Add(new Graphic() { Geometry = startLocation }); graphicsStops.Add(new Graphic() { Geometry = endLocation }); var stops = new FeaturesAsFeature(); stops.Features = graphicsStops; stops.SpatialReference = graphicsStops[0].Geometry.SpatialReference; routeParameters.Stops = stops; try { // Since we are ignoring cancellation just give a new token everytime var routeResult = await _routeTask.SolveAsync(routeParameters, new CancellationToken()); _isRouting = false; if (routeResult.Routes.Count > 0) { return(routeResult.Routes[0].RouteGraphic); } } catch (Exception) { // At the moment exception is thrown if route task couldn't solve the route so catch } _isRouting = false; return(null); }
private async Task CalculateRouteAsync() { try { progress.Visibility = Visibility.Visible; RouteParameters routeParams = await _routeTask.GetDefaultParametersAsync(); routeParams.OutSpatialReference = MyMapView.SpatialReference; routeParams.ReturnDirections = false; routeParams.SetStops(_stopsGraphicsOverlay.Graphics); 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)); 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 (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; } }
public async Task SolveRoute() { if (_stopsGraphicsLayer.Graphics.Count > 1) { try { _routeParams.ReturnPointBarriers = true; _routeParams.ReturnPolylineBarriers = true; _routeParams.ReturnPolygonBarriers = true; _routeParams.ReturnStops = true; _routeParams.ReturnZ = true; _routeParams.Stops = new FeaturesAsFeature(_stopsGraphicsLayer.Graphics); _routeParams.PointBarriers = new FeaturesAsFeature(_pointBarriersGraphicsLayer.Graphics); _routeParams.PolylineBarriers = new FeaturesAsFeature(_polylineBarriersGraphicsLayer.Graphics); _routeParams.PolygonBarriers = new FeaturesAsFeature(_polygonBarriersGraphicsLayer.Graphics); _routeParams.OutSpatialReference = mapView1.SpatialReference; _routeParams.DirectionsLengthUnit = LinearUnits.Kilometers; RouteResult routeResult = await _routeTask.SolveAsync(_routeParams); if (routeResult.Routes.Count > 0) { _routeGraphicsLayer.Graphics.Clear(); Graphic graphic = new Graphic(routeResult.Routes[0].RouteGraphic.Geometry); _routeGraphicsLayer.Graphics.Add(graphic); } } 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); } } }
private async void MyMap_Tapped(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e) { var mp = MyMap.ScreenToMap(e.GetPosition(MyMap)); Graphic g = new Graphic() { Geometry = mp }; var stopsLayer = MyMap.Layers["MyStopsGraphicsLayer"] as GraphicsLayer; var barriersLayer = MyMap.Layers["MyBarriersGraphicsLayer"] as GraphicsLayer; if (StopsRadioButton.IsChecked.Value) { stopsLayer.Graphics.Add(g); } else if (BarriersRadioButton.IsChecked.Value) { barriersLayer.Graphics.Add(g); } if (stopsLayer.Graphics.Count > 1) { try { var routeTask = new RouteTask(new Uri("http://tasks.arcgisonline.com/ArcGIS/rest/services/NetworkAnalysis/ESRI_Route_NA/NAServer/Route")); var result = await routeTask.SolveAsync(new RouteParameter() { Stops = new FeatureStops(stopsLayer.Graphics), Barriers = new FeatureBarriers(barriersLayer.Graphics), UseTimeWindows = false, OutSpatialReference = MyMap.SpatialReference }); if (result != null) { if (result.Directions != null && result.Directions.Count > 0) { var direction = result.Directions.FirstOrDefault(); if (direction != null && direction.RouteSummary != null) await new MessageDialog(string.Format("{0} minutes", direction.RouteSummary.TotalDriveTime.ToString("#0.000"))).ShowAsync(); } GraphicsLayer routeLayer = MyMap.Layers["MyRouteGraphicsLayer"] as GraphicsLayer; routeLayer.Graphics.Clear(); routeLayer.Graphics.AddRange(result.Routes); } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } } }
private void MyMap_MouseClick(object sender, ESRI.ArcGIS.Client.Map.MouseEventArgs e) { Graphic stop = new Graphic() { Geometry = e.MapPoint }; stopsGraphicsLayer.Graphics.Add(stop); if (stopsGraphicsLayer.Graphics.Count > 1) { if (routeTask.IsBusy) { routeTask.CancelAsync(); stopsGraphicsLayer.Graphics.RemoveAt(stopsGraphicsLayer.Graphics.Count - 1); } routeTask.SolveAsync(new RouteParameters() { Stops = stopsGraphicsLayer, UseTimeWindows = false, OutSpatialReference = MyMap.SpatialReference }); } }
private async Task CalculateRoute() { StartLocationText = string.Empty; EndLocationText = string.Empty; Directions = string.Empty; _routeGraphicsLayer.Graphics.Clear(); _stopsGraphicsLayer.Graphics.Clear(); try { // Mouseclick 1: MapPoint startLocation = await mapView1.Editor.RequestPointAsync(); _stopsGraphicsLayer.Graphics.Add(new Graphic() { Geometry = startLocation }); StartLocationText = " X: " + Math.Round(startLocation.X, 0).ToString() + " Y: " + Math.Round(startLocation.Y, 0).ToString(); // Mouseclick 2: MapPoint endLocation = await mapView1.Editor.RequestPointAsync(); _stopsGraphicsLayer.Graphics.Add(new Graphic() { Geometry = endLocation }); EndLocationText = " X: " + Math.Round(endLocation.X, 0).ToString() + " Y: " + Math.Round(endLocation.Y, 0).ToString(); Esri.ArcGISRuntime.Tasks.NetworkAnalyst.RouteParameters routeParams = await _routeTask.GetDefaultParametersAsync(); routeParams.OutSpatialReference = mapView1.SpatialReference; routeParams.ReturnDirections = true; routeParams.DirectionsLengthUnit = LinearUnits.Kilometers; routeParams.DirectionsLanguage = new System.Globalization.CultureInfo("en"); List <Graphic> graphicsStops = new List <Graphic>(); graphicsStops.Add(new Graphic(startLocation)); graphicsStops.Add(new Graphic(endLocation)); FeaturesAsFeature stops = new FeaturesAsFeature(graphicsStops); stops.SpatialReference = mapView1.SpatialReference; routeParams.Stops = stops; RouteResult routeResult = await _routeTask.SolveAsync(routeParams); if (routeResult.Routes.Count > 0) { Graphic graphic = new Graphic(routeResult.Routes[0].RouteGraphic.Geometry); _routeGraphicsLayer.Graphics.Add(graphic); List <string> directions = new List <string>(); foreach (var item in routeResult.Routes[0].RouteDirections) { directions.Add(" " + item.Text + "\r\n"); } Directions = String.Join <string>(String.Empty, directions); } } 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); } }
private async void GetDirections_Click(object sender, RoutedEventArgs e) { //Reset DirectionsStackPanel.Children.Clear(); var _stops = new List<Graphic>(); var _locator = new ESRI.ArcGIS.Runtime.Tasks.Locator(new Uri("http://tasks.arcgisonline.com/ArcGIS/rest/services/Locators/TA_Address_NA/GeocodeServer")); var routeLayer = MyMap.Layers["MyRouteGraphicsLayer"] as GraphicsLayer; routeLayer.Graphics.Clear(); try { //Geocode from address var fromLocation = await _locator.AddressToLocationsAsync(ParseAddress(FromTextBox.Text)); if (fromLocation.AddressCandidates != null && fromLocation.AddressCandidates.Count > 0) { AddressCandidate address = fromLocation.AddressCandidates.FirstOrDefault(); Graphic graphicLocation = new Graphic() { Geometry = address.Location, Symbol = LayoutRoot.Resources["FromSymbol"] as ISymbol }; graphicLocation.Attributes["address"] = address.Address; graphicLocation.Attributes["score"] = address.Score; _stops.Add(graphicLocation); routeLayer.Graphics.Add(graphicLocation); } //Geocode to address var toLocation = await _locator.AddressToLocationsAsync(ParseAddress(ToTextBox.Text)); if (toLocation.AddressCandidates != null && toLocation.AddressCandidates.Count > 0) { AddressCandidate address = toLocation.AddressCandidates.FirstOrDefault(); Graphic graphicLocation = new Graphic() { Geometry = address.Location, Symbol = LayoutRoot.Resources["ToSymbol"] as ISymbol }; graphicLocation.Attributes["address"] = address.Address; graphicLocation.Attributes["score"] = address.Score; _stops.Add(graphicLocation); routeLayer.Graphics.Add(graphicLocation); } //Get route between from and to var _routeParams = new RouteParameter() { ReturnRoutes = false, ReturnDirections = true, DirectionsLengthUnits = MapUnit.Miles, Stops = new FeatureStops(_stops), UseTimeWindows = false }; var _routeTask = new RouteTask(new Uri("http://tasks.arcgisonline.com/ArcGIS/rest/services/NetworkAnalysis/ESRI_Route_NA/NAServer/Route")); _routeParams.OutSpatialReference = MyMap.SpatialReference; var routeTaskResult = await _routeTask.SolveAsync(_routeParams); _directionsFeatureSet = routeTaskResult.Directions.FirstOrDefault(); routeLayer.Graphics.Add(new Graphic() { Geometry = _directionsFeatureSet.MergedGeometry, Symbol = LayoutRoot.Resources["RouteSymbol"] as ISymbol }); TotalDistanceTextBlock.Text = string.Format("Total Distance: {0}", FormatDistance(_directionsFeatureSet.RouteSummary.TotalLength, "miles")); TotalTimeTextBlock.Text = string.Format("Total Time: {0}", FormatTime(_directionsFeatureSet.RouteSummary.TotalTime)); TitleTextBlock.Text = _directionsFeatureSet.RouteName; int i = 1; foreach (Graphic graphic in _directionsFeatureSet.Graphics) { System.Text.StringBuilder text = new System.Text.StringBuilder(); text.AppendFormat("{0}. {1}", i, graphic.Attributes["text"]); if (i > 1 && i < _directionsFeatureSet.Graphics.Count) { string distance = FormatDistance(Convert.ToDouble(graphic.Attributes["length"]), "miles"); string time = null; if (graphic.Attributes.ContainsKey("time")) { time = FormatTime(Convert.ToDouble(graphic.Attributes["time"])); } if (!string.IsNullOrEmpty(distance) || !string.IsNullOrEmpty(time)) text.Append(" ("); text.Append(distance); if (!string.IsNullOrEmpty(distance) && !string.IsNullOrEmpty(time)) text.Append(", "); text.Append(time); if (!string.IsNullOrEmpty(distance) || !string.IsNullOrEmpty(time)) text.Append(")"); } TextBlock textBlock = new TextBlock() { Text = text.ToString(), Tag = graphic, Margin = new Thickness(4) }; textBlock.Tapped += TextBlock_Tapped; DirectionsStackPanel.Children.Add(textBlock); i++; } MyMap.ZoomTo(_directionsFeatureSet.RouteSummary.Extent.Expand(0.6)); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } }
void SolveRoute(MapPoint start, MapPoint end) { // The Esri World Network Analysis Services requires an ArcGIS Online Subscription. // In this sample use the North America only service on tasks.arcgisonline.com. var routeTask = new RouteTask("http://tasks.arcgisonline.com/ArcGIS/rest/services/NetworkAnalysis/ESRI_Route_NA/NAServer/Route"); // Create a new list of graphics to send to the route task. Note don't use the graphcis returned from find // as the attributes cause issues with the route finding. var stops = new List<Graphic>() { new Graphic() { Geometry = start}, new Graphic() { Geometry = end} }; var routeParams = new RouteParameters() { Stops = stops, UseTimeWindows = false, OutSpatialReference = MyMap.SpatialReference, ReturnDirections = false, IgnoreInvalidLocations = true }; routeTask.Failed += (s, e) => { MessageBox.Show("Route Task failed:" + e.Error); }; // Register an inline handler for the SolveCompleted event. routeTask.SolveCompleted += (s, e) => { // Add the returned route to the Map var myRoute = new Graphic() { Geometry = e.RouteResults[0].Route.Geometry, Symbol = new SimpleLineSymbol() { Width = 10, Color = new SolidColorBrush(Color.FromArgb(127, 0, 0, 255)) } }; // Add a MapTip decimal totalTime = (decimal)e.RouteResults[0].Route.Attributes["Total_Time"]; string tip = string.Format("{0} minutes", totalTime.ToString("#0.0")); myRoute.Attributes.Add("TIP", tip); MyRoutesGraphicsLayer.Graphics.Add(myRoute); }; // Call the SolveAsync method routeTask.SolveAsync(routeParams); }
private void GetDirectionsFromAtoB(Graphic origin, Graphic destination) { if (origin == null || destination == null) return; var l = MyMap.Layers["RouteResultsLayer"] as GraphicsLayer; l.Graphics.Clear(); var stops = new List<Graphic>(); stops.Add(origin); stops.Add(destination); #region RouteTask - Gets directions from A (Origin) to B (Destination) var routeTask = new RouteTask(ROUTE_URL); routeTask.SolveCompleted += (s, e) => { MyProgressBar.IsIndeterminate = false; var featureSet = e.RouteResults.FirstOrDefault().Directions; var g = new Graphic() { Geometry = featureSet.MergedGeometry }; g.Geometry.SpatialReference = MyMap.SpatialReference; l.Graphics.Add(g); MyMap.ZoomTo(Expand(l.FullExtent)); BufferPathGeometry(g); // widens the scope of path geometry. }; routeTask.Failed += (s, e) => { MyProgressBar.IsIndeterminate = false; MessageBox.Show(string.Format("Get directions to '{0}' failed with error '{1}'", pointB.Geometry as MapPoint, e.Error.Message)); }; MyProgressBar.IsIndeterminate = true; routeTask.SolveAsync(new RouteParameters() { DirectionsLengthUnits = esriUnits.esriMiles, OutSpatialReference = MyMap.SpatialReference, Stops = stops, ReturnDirections = true }); #endregion }
private void GetDirectionToDestination(Graphic destination) { if (myLocation == null || destination == null) return; EnableDirectionsButton(true); DirectionsStackPanel.Children.Clear(); UpdateLayer("FindResultsLayer", false, false); var d = UpdateLayer("DestinationLayer", true, true); d.Graphics.Add(destination); var l = UpdateLayer("RouteResultsLayer", true, true); var stops = new List<Graphic>(); stops.Add(myLocation); stops.Add(destination); #region RouteTask - Gets directions from A (Current Location) to B (Destination) var routeTask = new RouteTask(ROUTE_URL); routeTask.SolveCompleted += (s, e) => { MyProgressBar.IsIndeterminate = false; var featureSet = e.RouteResults.FirstOrDefault().Directions; l.Graphics.Add(new Graphic() { Geometry = featureSet.MergedGeometry }); UpdateDirectionsPanel(featureSet); MyMap.ZoomTo(Expand(l.FullExtent)); }; routeTask.Failed += (s, e) => { MyProgressBar.IsIndeterminate = false; MessageBox.Show(string.Format("Get directions to '{0}' failed with error '{1}'", destination.Geometry as MapPoint, e.Error.Message)); ShowElement(MyMap); }; MyProgressBar.IsIndeterminate = true; routeTask.SolveAsync(new RouteParameters() { DirectionsLengthUnits = esriUnits.esriMiles, OutSpatialReference = MyMap.SpatialReference, Stops = stops, ReturnDirections = true }); #endregion }