Click or drag to resize

RouteTask Class

Class for route tasks (online and local).
Inheritance Hierarchy
SystemObject
  Esri.ArcGISRuntime.Tasks.NetworkAnalysisRouteTask

Namespace:  Esri.ArcGISRuntime.Tasks.NetworkAnalysis
Assembly:  Esri.ArcGISRuntime (in Esri.ArcGISRuntime.dll) Version: 100.9.0.0
Syntax
C#
public sealed class RouteTask

The RouteTask type exposes the following members.

Properties
  NameDescription
Public propertyCredential
Gets or sets the security credential used to access a remote task
Public propertyCode exampleRouteTaskInfo
Gets route task info. RouteTask must be loaded before accessing this property.
Public propertyTransportationNetworkDataset
Gets the transportation network dataset associated with the route task.
Public propertyUri
Gets the Uri of the route task.
Top
Methods
  NameDescription
Public methodStatic memberCode exampleCreateAsync(TransportationNetworkDataset)
Creates a route task from a transportation network dataset.
Public methodStatic memberCode exampleCreateAsync(String, String)
Creates a route task from a local geodatabase.
Public methodStatic memberCode exampleCreateAsync(Uri, Credential)
Creates a route task from an online URI.
Public methodCode exampleCreateDefaultParametersAsync
Creates default parameters for the route task.
Public methodCreateParametersAsync(FeatureCollection)
Imports route parameters from feature collection and then adjusts imported parameters to current Route task.
Public methodCreateParametersAsync(PortalItem)
Imports route parameters from portal item and then adjusts imported parameters to current Route task.
Public methodStatic memberCreateRouteResultAsync(FeatureCollection)
Imports a route result from a Route Layer feature collection.
Public methodStatic memberCreateRouteResultAsync(PortalItem)
Imports route result from portal item.
Public methodCode exampleSolveRouteAsync
Solves a route with the specified parameters.
Top
Examples

Android

Example Name: FindRoute

Display directions for a route between two points.

Code example screen shot.

C#
// Copyright 2017 Esri.
// 
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific
// language governing permissions and limitations under the License.

using Android.App;
using Android.OS;
using Android.Widget;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Symbology;
using Esri.ArcGISRuntime.Tasks.NetworkAnalysis;
using Esri.ArcGISRuntime.UI;
using Esri.ArcGISRuntime.UI.Controls;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;

namespace ArcGISRuntime.Samples.FindRoute
{
    [Activity (ConfigurationChanges=Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize)]
    [ArcGISRuntime.Samples.Shared.Attributes.Sample(
        name: "Find route",
        category: "Network analysis",
        description: "Display directions for a route between two points.",
        instructions: "For simplicity, the sample comes loaded with a start and end stop. You can tap on the Find Route button to display a route between these stops. Once the route is generated, turn-by-turn directions are shown in a list.",
        tags: new[] { "directions", "driving", "navigation", "network", "network analysis", "route", "routing", "shortest path", "turn-by-turn" })]
    public class FindRoute : Activity
    {
        // Hold a reference to the map view.
        private MapView _myMapView;

        // List of stops on the route ('from' and 'to')
        private List<Stop> _routeStops;

        // Graphics overlay to display stops and the route result
        private GraphicsOverlay _routeGraphicsOverlay;

        // URI for the San Diego route service
        private Uri _sanDiegoRouteServiceUri = new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/NetworkAnalysis/SanDiego/NAServer/Route");

        // URIs for picture marker images
        private Uri _checkedFlagIconUri = new Uri("https://static.arcgis.com/images/Symbols/Transportation/CheckeredFlag.png");

        private Uri _carIconUri = new Uri("https://static.arcgis.com/images/Symbols/Transportation/CarRedFront.png");

        // UI control to show/hide directions dialog (private scope so it can be enabled/disabled as needed)
        private Button _showHideDirectionsButton;

        // Dialog for showing driving directions
        private AlertDialog _directionsDialog;

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            Title = "Find a route";

            // Create the UI
            CreateLayout();

            // Initialize the app
            Initialize();
        }

        private void CreateLayout()
        {
            // Create a new layout for the entire page
            LinearLayout layout = new LinearLayout(this) { Orientation = Orientation.Vertical };

            // Create a new layout for the toolbar (buttons)
            LinearLayout toolbar = new LinearLayout(this) { Orientation = Orientation.Horizontal };

            // Create a button to solve the route and add it to the toolbar
            Button solveRouteButton = new Button(this) { Text = "Solve Route" };
            solveRouteButton.Click += SolveRouteClick;
            toolbar.AddView(solveRouteButton);

            // Create a button to reset the route display, add it to the toolbar
            Button resetButton = new Button(this) { Text = "Reset" };
            resetButton.Click += ResetClick;
            toolbar.AddView(resetButton);

            // Create a button to show or hide the route directions, add it to the toolbar
            _showHideDirectionsButton = new Button(this) { Text = "Directions" };
            _showHideDirectionsButton.Click += ShowDirectionsClick;
            _showHideDirectionsButton.Enabled = false;
            toolbar.AddView(_showHideDirectionsButton);

            // Add the toolbar to the layout
            layout.AddView(toolbar);

            // Add the map view to the layout
            _myMapView = new MapView(this);
            layout.AddView(_myMapView);

            // Show the layout in the app
            SetContentView(layout);
        }

        private void Initialize()
        {
            // Define the route stop locations (points)
            MapPoint fromPoint = new MapPoint(-117.15494348793044, 32.706506537686927, SpatialReferences.Wgs84);
            MapPoint toPoint = new MapPoint(-117.14905088669816, 32.735308180609138, SpatialReferences.Wgs84);

            // Create Stop objects with the points and add them to a list of stops
            Stop stop1 = new Stop(fromPoint);
            Stop stop2 = new Stop(toPoint);
            _routeStops = new List<Stop> { stop1, stop2 };

            // Picture marker symbols: from = car, to = checkered flag
            PictureMarkerSymbol carSymbol = new PictureMarkerSymbol(_carIconUri)
            {
                Height = 40,
                Width = 40
            };
            PictureMarkerSymbol flagSymbol = new PictureMarkerSymbol(_checkedFlagIconUri)
            {
                Height = 40,
                Width =  40,
                // Offset the icon so that it is anchored at the bottom of the flagpole
                OffsetX = 20,
                OffsetY = 20
            };

            // Create graphics for the stops
            Graphic fromGraphic = new Graphic(fromPoint, carSymbol)
            {
                // Make sure the icons are shown over the route line
                ZIndex = 1
            };
            Graphic toGraphic = new Graphic(toPoint, flagSymbol)
            {
                ZIndex = 1
            };

            // Create the graphics overlay and add the stop graphics
            _routeGraphicsOverlay = new GraphicsOverlay();
            _routeGraphicsOverlay.Graphics.Add(fromGraphic);
            _routeGraphicsOverlay.Graphics.Add(toGraphic);

            // Get an Envelope that covers the area of the stops (and a little more)
            Envelope routeStopsExtent = new Envelope(fromPoint, toPoint);
            EnvelopeBuilder envBuilder = new EnvelopeBuilder(routeStopsExtent);
            envBuilder.Expand(1.5);

            // Create a new viewpoint apply it to the map view when the spatial reference changes
            Viewpoint sanDiegoViewpoint = new Viewpoint(envBuilder.ToGeometry());
            _myMapView.SpatialReferenceChanged += (s, e) => _myMapView.SetViewpoint(sanDiegoViewpoint);

            // Add a new Map and the graphics overlay to the map view
            _myMapView.Map = new Map(Basemap.CreateStreets());
            _myMapView.GraphicsOverlays.Add(_routeGraphicsOverlay);
        }

        private async void SolveRouteClick(object sender, EventArgs e)
        {
            try
            {
                // Create a new route task using the San Diego route service URI
                RouteTask solveRouteTask = await RouteTask.CreateAsync(_sanDiegoRouteServiceUri);

                // Get the default parameters from the route task (defined with the service)
                RouteParameters routeParams = await solveRouteTask.CreateDefaultParametersAsync();

                // Make some changes to the default parameters
                routeParams.ReturnStops = true;
                routeParams.ReturnDirections = true;

                // Set the list of route stops that were defined at startup
                routeParams.SetStops(_routeStops);

                // Solve for the best route between the stops and store the result
                RouteResult solveRouteResult = await solveRouteTask.SolveRouteAsync(routeParams);

                // Get the first (should be only) route from the result
                Route firstRoute = solveRouteResult.Routes.First();

                // Get the route geometry (polyline)
                Polyline routePolyline = firstRoute.RouteGeometry;

                // Create a thick purple line symbol for the route
                SimpleLineSymbol routeSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.Purple, 8.0);

                // Create a new graphic for the route geometry and add it to the graphics overlay
                Graphic routeGraphic = new Graphic(routePolyline, routeSymbol)
                {
                    ZIndex = 0
                };
                _routeGraphicsOverlay.Graphics.Add(routeGraphic);

                // Get a list of directions for the route and display it in the list box
                CreateDirectionsDialog(firstRoute.DirectionManeuvers.Select(d => d.DirectionText));
                _showHideDirectionsButton.Enabled = true;
            }
            catch (Exception ex)
            {
                new AlertDialog.Builder(this).SetMessage(ex.ToString()).SetTitle("Error").Show();
            }
        }

        private void ResetClick(object sender, EventArgs e)
        {
            // Remove the route graphic from the graphics overlay (only line graphic in the collection)
            int graphicsCount = _routeGraphicsOverlay.Graphics.Count;
            for (int i = graphicsCount; i > 0; i--)
            {
                // Get this graphic and see if it has line geometry
                Graphic g = _routeGraphicsOverlay.Graphics[i - 1];
                if (g.Geometry.GeometryType == GeometryType.Polyline)
                {
                    // Remove the graphic from the overlay
                    _routeGraphicsOverlay.Graphics.Remove(g);
                }
            }

            // Disable the button to show the directions dialog
            _showHideDirectionsButton.Enabled = false;
        }

        private void ShowDirectionsClick(object sender, EventArgs e)
        {
            // Show the directions dialog
            if (_directionsDialog != null)
            {
                _directionsDialog.Show();
            }
        }

        private void CreateDirectionsDialog(IEnumerable<string> directions)
        {
            // Create a dialog to show route directions
            AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);

            // Create the layout
            LinearLayout dialogLayout = new LinearLayout(this)
            {
                Orientation = Orientation.Vertical
            };

            // Create a list box for showing the route directions
            ListView directionsList = new ListView(this);
            ArrayAdapter<string> directionsAdapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, directions.ToArray());
            directionsList.Adapter = directionsAdapter;
            dialogLayout.AddView(directionsList);

            // Add the controls to the dialog
            dialogBuilder.SetView(dialogLayout);
            dialogBuilder.SetTitle("Route Directions");

            // Create the dialog (don't show it)
            _directionsDialog = dialogBuilder.Create();
        }
    }
}
Examples

Xamarin Forms Android

Example Name: MobileMapSearchAndRoute

Display maps and use locators to enable search and routing offline using a Mobile Map Package.

Code example screen shot.

C#
// Copyright 2019 Esri.
// 
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific
// language governing permissions and limitations under the License.

using ArcGISRuntime.Samples.Managers;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Symbology;
using Esri.ArcGISRuntime.Tasks.Geocoding;
using Esri.ArcGISRuntime.Tasks.NetworkAnalysis;
using Esri.ArcGISRuntime.UI;
using Esri.ArcGISRuntime.UI.Controls;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace ArcGISRuntimeXamarin.Samples.MobileMapSearchAndRoute
{
    [ArcGISRuntime.Samples.Shared.Attributes.Sample(
        name: "Mobile map (search and route)",
        category: "Map",
        description: "Display maps and use locators to enable search and routing offline using a Mobile Map Package.",
        instructions: "A list of maps from a mobile map package will be displayed. If the map contains transportation networks, the list item will have a navigation icon. Tap on a map in the list to open it. If a locator task is available, tap on the map to reverse geocode the location's address. If transportation networks are available, a route will be calculated between geocode locations.",
        tags: new[] { "disconnected", "field mobility", "geocode", "network", "network analysis", "offline", "routing", "search", "transportation" })]
    [ArcGISRuntime.Samples.Shared.Attributes.OfflineData("260eb6535c824209964cf281766ebe43")]
    public partial class MobileMapSearchAndRoute : ContentPage
    {
        // Hold references to map resources for easy access.
        public ObservableCollection<Map> Maps { get; } = new ObservableCollection<Map>();
        private LocatorTask _packageLocator;
        private TransportationNetworkDataset _networkDataset;

        // Overlays for use in visualizing routes.
        private GraphicsOverlay _routeOverlay;
        private GraphicsOverlay _waypointOverlay;

        // Track the start and end point for route calculation.
        private MapPoint _startPoint;
        private MapPoint _endPoint;

        public MobileMapSearchAndRoute()
        {
            InitializeComponent();
            Initialize();
        }

        private async void Initialize()
        {
            // Get the path to the package on disk.
            string filePath = DataManager.GetDataFolder("260eb6535c824209964cf281766ebe43", "SanFrancisco.mmpk");

            // Open the map package.
            MobileMapPackage package = await OpenMobileMapPackage(filePath);

            // Populate the list of maps.
            foreach (Map map in package.Maps)
            {
                await map.LoadAsync();
                Maps.Add(map);
            }

            // Show the first map by default.
            MyMapView.Map = Maps.First();

            // Populate the map list in the UI.
            MapListView.ItemsSource = Maps;

            // Get the locator task from the package.
            _packageLocator = package.LocatorTask;

            // Create and add an overlay for showing a route.
            _routeOverlay = new GraphicsOverlay();
            _routeOverlay.Renderer = new SimpleRenderer
            {
                Symbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.Blue, 3)
            };
            MyMapView.GraphicsOverlays.Add(_routeOverlay);

            // Create and add an overlay for showing waypoints/stops.
            _waypointOverlay = new GraphicsOverlay();
            MyMapView.GraphicsOverlays.Add(_waypointOverlay);

            // Enable tap-to-reverse geocode and tap-to-route.
            MyMapView.GeoViewTapped += MapView_Tapped;
        }

        private async Task<MobileMapPackage> OpenMobileMapPackage(string path)
        {
            // Open the map package.
            MobileMapPackage package = await MobileMapPackage.OpenAsync(path);

            // Load the package.
            await package.LoadAsync();

            // Return the opened package.
            return package;
        }

        private async void MapView_Tapped(object sender, Esri.ArcGISRuntime.Xamarin.Forms.GeoViewInputEventArgs e)
        {
            // Handle routing.
            try
            {
                await ProcessRouteRequest(e.Location);
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
                await Application.Current.MainPage.DisplayAlert("Error", "Couldn't geocode or route.", "OK");
            }
        }

        private async Task ShowGeocodeResult(MapPoint tappedPoint)
        {
            // Reverse geocode to get an address.
            IReadOnlyList<GeocodeResult> results = await _packageLocator.ReverseGeocodeAsync(tappedPoint);

            // Process the address into usable strings.
            string address = results.First().Label;

            // Show the address in a callout.
            MyMapView.ShowCalloutAt(tappedPoint, new CalloutDefinition(address));
        }

        private async Task ProcessRouteRequest(MapPoint tappedPoint)
        {
            // Clear any existing overlays.
            _routeOverlay.Graphics.Clear();
            MyMapView.DismissCallout();

            // Return if there is no network available for routing.
            if (_networkDataset == null)
            {
                await ShowGeocodeResult(tappedPoint);
                return;
            }

            // Set the start point if it hasn't been set.
            if (_startPoint == null)
            {
                _startPoint = tappedPoint;

                await ShowGeocodeResult(tappedPoint);

                // Show the start point.
                _waypointOverlay.Graphics.Add(await GraphicForPoint(_startPoint));

                return;
            }

            if (_endPoint == null)
            {
                await ShowGeocodeResult(tappedPoint);

                // Show the end point.
                _endPoint = tappedPoint;
                _waypointOverlay.Graphics.Add(await GraphicForPoint(_endPoint));

                // Create the route task from the local network dataset.
                RouteTask routingTask = await RouteTask.CreateAsync(_networkDataset);

                // Configure route parameters for the route between the two tapped points.
                RouteParameters routingParameters = await routingTask.CreateDefaultParametersAsync();
                List<Stop> stops = new List<Stop> { new Stop(_startPoint), new Stop(_endPoint) };
                routingParameters.SetStops(stops);

                // Get the first route result.
                RouteResult result = await routingTask.SolveRouteAsync(routingParameters);
                Route firstRoute = result.Routes.First();

                // Show the route on the map. Note that symbology for the graphics overlay is defined in Initialize().
                Polyline routeLine = firstRoute.RouteGeometry;
                _routeOverlay.Graphics.Add(new Graphic(routeLine));

                return;
            }

            // Reset graphics and route.
            _routeOverlay.Graphics.Clear();
            _waypointOverlay.Graphics.Clear();
            _startPoint = null;
            _endPoint = null;
        }

        private async void Map_Selected(object sender, EventArgs e)
        {
            // Clear existing overlays.
            MyMapView.DismissCallout();
            _waypointOverlay.Graphics.Clear();
            _routeOverlay.Graphics.Clear();

            try
            {
                ListView sendingList = (ListView)sender;
                // Get the selected map.
                Map selectedMap = sendingList.SelectedItem as Map;

                // Show the map in the view.
                MyMapView.Map = selectedMap;

                // Get the transportation network if there is one. Will be set to null otherwise.
                _networkDataset = selectedMap.TransportationNetworks.FirstOrDefault();
            }
            catch (Exception exception)
            {
                Debug.WriteLine(exception);
                await Application.Current.MainPage.DisplayAlert("Error", e.ToString(), "OK");
            }
        }

        private async Task<Graphic> GraphicForPoint(MapPoint point)
        {
#if WINDOWS_UWP
            // Get current assembly that contains the image
            Assembly currentAssembly = GetType().GetTypeInfo().Assembly;
#else
            // Get current assembly that contains the image
            Assembly currentAssembly = Assembly.GetExecutingAssembly();
#endif

            // Get image as a stream from the resources
            // Picture is defined as EmbeddedResource and DoNotCopy
            Stream resourceStream = currentAssembly.GetManifestResourceStream(
                "ArcGISRuntime.Resources.PictureMarkerSymbols.pin_star_blue.png");

            // Create new symbol using asynchronous factory method from stream
            PictureMarkerSymbol pinSymbol = await PictureMarkerSymbol.CreateAsync(resourceStream);
            pinSymbol.Width = 60;
            pinSymbol.Height = 60;
            // The image is a pin; offset the image so that the pinpoint
            //     is on the point rather than the image's true center
            pinSymbol.LeaderOffsetX = 30;
            pinSymbol.OffsetY = 14;
            return new Graphic(point, pinSymbol);
        }
    }
}
XAML
<?xml version="1.0" encoding="utf-8"?>

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:esriUI="clr-namespace:Esri.ArcGISRuntime.Xamarin.Forms;assembly=Esri.ArcGISRuntime.Xamarin.Forms"
             xmlns:mapping="clr-namespace:Esri.ArcGISRuntime.Mapping;assembly=Esri.ArcGISRuntime"
             xmlns:resources="clr-namespace:Forms.Resources;assembly=ArcGISRuntime"
             xmlns:converters="clr-namespace:ArcGISRuntimeXamarin.Converters;assembly=ArcGISRuntime"
             xmlns:converters1="clr-namespace:Forms.Converters"
             x:Class="ArcGISRuntimeXamarin.Samples.MobileMapSearchAndRoute.MobileMapSearchAndRoute">
    <ContentPage.Resources>
        <converters:NullOrEmptyToVisibilityConverter x:Key="NullToVisibilityConverter" />
        <converters1:ItemToImageSourceConverter x:Key="ItemToImageSourceConverter" />
    </ContentPage.Resources>
    <RelativeLayout>
        <esriUI:MapView x:Name="MyMapView" Style="{StaticResource MapWithFormStyle}"
                        BindingContext="{x:Reference Name=ResponsiveFormContainer}" />
        <resources:ResponsiveFormContainer x:Name="ResponsiveFormContainer">
            <StackLayout>
                <Label
                    Text="Select a map from the package. If a network is available, you can route between tapped points. If a locator is available, the address for each tapped point will be displayed in a callout."
                    LineBreakMode="WordWrap" />
                <ListView x:Name="MapListView"
                          ItemSelected="Map_Selected"
                          HeightRequest="150"
                          RowHeight="50"
                          Margin="0,5,0,0">
                    <ListView.ItemTemplate>
                        <DataTemplate x:DataType="mapping:Map">
                            <ViewCell>
                                <Grid>
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="50" />
                                        <ColumnDefinition Width="Auto" />
                                        <ColumnDefinition Width="*" />
                                    </Grid.ColumnDefinitions>
                                    <Image Grid.Column="0"
                                           Source="{Binding Item, Converter={StaticResource ItemToImageSourceConverter}}" />
                                    <Image Grid.Column="1"
                                           Source="{resources:ImageResource ArcGISRuntime.Resources.routingSymbol.png}"
                                           HeightRequest="25" WidthRequest="25"
                                           Margin="5"
                                           IsVisible="{Binding TransportationNetworks,Converter={StaticResource NullToVisibilityConverter}}" />
                                    <Label Grid.Column="2"
                                           Text="{Binding Item.Title}"
                                           VerticalTextAlignment="Center"
                                           HorizontalTextAlignment="Start" />
                                </Grid>
                            </ViewCell>
                        </DataTemplate>
                    </ListView.ItemTemplate>
                </ListView>
            </StackLayout>
        </resources:ResponsiveFormContainer>
    </RelativeLayout>
</ContentPage>
See Also
Additional Examples
Hyperlink to ExampleDescription
FindRouteDisplay directions for a route between two points.
MobileMapSearchAndRouteDisplay maps and use locators to enable search and routing offline using a Mobile Map Package.
NavigateRouteUse a routing service to navigate between points.
NavigateRouteReroutingNavigate between two points and dynamically recalculate an alternate route when the original route is unavailable.
OfflineRoutingSolve a route on-the-fly using offline data.
RouteAroundBarriersFind a route that reaches all stops without crossing any barriers.