Skip To Content ArcGIS for Developers Sign In Dashboard

ArcGIS Runtime SDK for .NET

Navigate route with rerouting

This code sample is available for these platforms:
View Sample on GitHub

Navigate between two points and dynamically recalculate an alternate route when the original route is unavailable.

Image of navigate route with rerouting

Use case

While traveling between destinations, field workers use navigation to get live directions based on their locations. In cases where a field worker makes a wrong turn, or if the route suggested is blocked due to a road closure, it is necessary to calculate an alternate route to the original destination.

How to use the sample

Tap 'Navigate' to simulate traveling and to receive directions from a preset starting point to a preset destination. Observe how the route is recalculated when the simulation does not follow the suggested route. Tap 'Recenter' to refocus on the location display.

How it works

  1. Create a RouteTask using a URL to an online route service.
  2. Generate default RouteParameters using RouteTask.CreateDefaultParametersAsync().
  3. Set ReturnStops and ReturnDirections on the parameters to true.
  4. Add Stops to the parameters stops collection for each destination.
  5. Solve the route using RouteTask.SolveRouteAsync(routeParameters) to get a RouteResult.
  6. Create a RouteTracker using the route result, and the index of the desired route to take.
  7. Enable rerouting in the route tracker with .EnableReroutingAsync(RouteTask, RouteParameters, ReroutingStrategy, false). The Boolean specifies visitFirstStopOnStart and is false by default. Use ReroutingStrategy.ToNextWaypoint to specify that in the case of a reroute the new route goes from present location to next waypoint or stop.
  8. Use .TrackLocationAsync(LocationDataSource.Location) to track the location of the device and update the route tracking status.
  9. Add a listener to capture TrackingStatusChangedEvent, and then get the TrackingStatus and use it to display updated route information. Tracking status includes a variety of information on the route progress, such as the remaining distance, remaining geometry or traversed geometry (represented by a Polyline), or the remaining time (Double), amongst others.
  10. Add a NewVoiceGuidanceListener to get the VoiceGuidance whenever new instructions are available. From the voice guidance, get the string representing the directions and use a text-to-speech engine to output the maneuver directions.
  11. You can also query the tracking status for the current DirectionManeuver index, retrieve that maneuver from the Route and get its direction text to display in the GUI.
  12. To establish whether the destination has been reached, get the DestinationStatus from the tracking status. If the destination status is Reached, and the RemainingDestinationCount is 1, you have arrived at the destination and can stop routing. If there are several destinations in your route, and the remaining destination count is greater than 1, switch the route tracker to the next destination.

Relevant API

  • DestinationStatus
  • DirectionManeuver
  • Location
  • LocationDataSource
  • ReroutingStrategy
  • Route
  • RouteParameters
  • RouteTask
  • RouteTracker
  • Stop
  • VoiceGuidance

Offline data

A GPX file provides a simulated path for the device to demonstrate routing while travelling. Navigate a Route GPX Track A geodatabase contains a road network for San Diego. San Diego Geodatabase

About the data

The route taken in this sample goes from the San Diego Convention Center, site of the annual Esri User Conference, to the Fleet Science Center, San Diego.

Additional information

The route tracker will start a rerouting calculation automatically as necessary when the device's location indicates that it is off-route. The route tracker also validates that the device is "on" the transportation network, if it is not (e.g. in a parking lot) rerouting will not occur until the device location indicates that it is back "on" the transportation network.


directions, maneuver, navigation, route, turn-by-turn, voice

Sample Code

// 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:
// 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 Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Location;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Timers;
using System.Xml;

namespace ArcGISRuntimeXamarin.Samples.NavigateRouteRerouting
    public class GpxProvider : LocationDataSource
        private Timer _driveTimer;
        private double _timerValue = 500;

        private List<MapPoint> _gpsPoints;
        private int _nodeIndex;

        private double _course;
        private double _speed;

        public GpxProvider(string gpxFilePath)
            _gpsPoints = new List<MapPoint>();

            // Read the GPX data.

            // Create a timer for updating the location.
            _driveTimer = new Timer(_timerValue)
                Enabled = false
            _driveTimer.Elapsed += TimerElapsed;

        private void TimerElapsed(object sender, ElapsedEventArgs e)
            // Check that there are remaining nodes.
            if (_nodeIndex > _gpsPoints.Count - 1)
                _driveTimer.Enabled = false;

            // Check if there is a previous node.
            if (_nodeIndex > 0)
                // Get the distance between the current node and the previous node.
                GeodeticDistanceResult distance = GeometryEngine.DistanceGeodetic(_gpsPoints[_nodeIndex], _gpsPoints[_nodeIndex - 1], LinearUnits.Meters, AngularUnits.Degrees, GeodeticCurveType.Geodesic);

                // Get the course in degrees.
                _course = distance.Azimuth2;

                // Calculate the speed in m/s by using the distance and the timer interval.
                _speed = distance.Distance / (_timerValue / 1000);

            // Set the new location.
            UpdateLocation(new Location(_gpsPoints[_nodeIndex], 5, _speed, _course, false));

            // Increment the node index.

        protected override Task OnStartAsync()
            _driveTimer.Enabled = true;
            return Task.FromResult(true);

        protected override Task OnStopAsync()
            _driveTimer.Enabled = false;
            return Task.FromResult(true);

        private void ReadLocations(string gpx)
            // Load the GPX data.
            XmlDocument gpxDoc = new XmlDocument();
            XmlNamespaceManager namespaceManager = new XmlNamespaceManager(gpxDoc.NameTable);

            // Get the schema information for GPX.
            namespaceManager.AddNamespace("x", "");

            // Get the tracking points from the GPX data.
            XmlNodeList xmlNodes;
            xmlNodes = gpxDoc.SelectNodes("//x:trkpt", namespaceManager);

            foreach (XmlNode locationNode in xmlNodes)
                // Get the location from the node.
                string longitude = locationNode.Attributes["lon"].Value;
                string latitude = locationNode.Attributes["lat"].Value;
                double.TryParse(longitude, out double x);
                double.TryParse(latitude, out double y);
                _gpsPoints.Add(new MapPoint(x, y, SpatialReferences.Wgs84));
            BindingContext="{x:Reference Name=ResponsiveFormContainer}"
            Style="{StaticResource MapWithFormStyle}" />
        <resources:ResponsiveFormContainer x:Name="ResponsiveFormContainer">
                    <RowDefinition Height="auto" />
                    <RowDefinition Height="auto" />
                <Grid Grid.Row="0">
                        <ColumnDefinition Width="*" />
                        <ColumnDefinition Width="*" />
                        Text="Navigate" />
                        Text="Recenter" />
                    Text="" />
// 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:
// 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.Location;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Navigation;
using Esri.ArcGISRuntime.Symbology;
using Esri.ArcGISRuntime.Tasks.NetworkAnalysis;
using Esri.ArcGISRuntime.UI;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Xamarin.Forms;
using static Xamarin.Essentials.TextToSpeech;
using Color = System.Drawing.Color;

namespace ArcGISRuntimeXamarin.Samples.NavigateRouteRerouting
        name: "Navigate route with rerouting",
        category: "Network analysis",
        description: "Navigate between two points and dynamically recalculate an alternate route when the original route is unavailable.",
        instructions: "Tap 'Navigate' to simulate traveling and to receive directions from a preset starting point to a preset destination. Observe how the route is recalculated when the simulation does not follow the suggested route. Tap 'Recenter' to refocus on the location display.",
        tags: new[] { "directions", "maneuver", "navigation", "route", "turn-by-turn", "voice" })]
    [ArcGISRuntime.Samples.Shared.Attributes.OfflineData("567e14f3420d40c5a206e5c0284cf8fc", "91e7e6be79cc4d2f8416eff867674c1e")]
    public partial class NavigateRouteRerouting : ContentPage, IDisposable
        // Variables for tracking the navigation route.
        private RouteTracker _tracker;
        private RouteResult _routeResult;
        private Route _route;
        private RouteTask _routeTask;
        private RouteParameters _routeParams;

        // List of driving directions for the route.
        private IReadOnlyList<DirectionManeuver> _directionsList;

        // Cancellation token for speech synthesizer.
        private CancellationTokenSource _speechToken = new CancellationTokenSource();

        // Graphics to show progress along the route.
        private Graphic _routeAheadGraphic;
        private Graphic _routeTraveledGraphic;

        // San Diego Convention Center.
        private readonly MapPoint _conventionCenter = new MapPoint(-117.160386727, 32.706608, SpatialReferences.Wgs84);

        // RH Fleet Aerospace Museum.
        private readonly MapPoint _aerospaceMuseum = new MapPoint(-117.146678, 32.730463, SpatialReferences.Wgs84);

        // GPX file that contains simulated location data for driving route.
        private readonly string _gpxPath = DataManager.GetDataFolder("91e7e6be79cc4d2f8416eff867674c1e", "navigate_a_route_detour.gpx");

        // Path to the network geodatabase for San Diego.
        private readonly string _networkGeodatabasePath = DataManager.GetDataFolder("567e14f3420d40c5a206e5c0284cf8fc", "sandiego.geodatabase");

        public NavigateRouteRerouting()

        private async void Initialize()
                // Create the map view.
                MyMapView.Map = new Map(Basemap.CreateStreets());

                // Create the route task, using the routing service.
                _routeTask = await RouteTask.CreateAsync(_networkGeodatabasePath, "Streets_ND");

                // Get the default route parameters.
                _routeParams = await _routeTask.CreateDefaultParametersAsync();

                // Explicitly set values for parameters.
                _routeParams.ReturnDirections = true;
                _routeParams.ReturnStops = true;
                _routeParams.ReturnRoutes = true;
                _routeParams.OutputSpatialReference = SpatialReferences.Wgs84;

                // Create stops for each location.
                Stop stop1 = new Stop(_conventionCenter) { Name = "San Diego Convention Center" };
                Stop stop2 = new Stop(_aerospaceMuseum) { Name = "RH Fleet Aerospace Museum" };

                // Assign the stops to the route parameters.
                List<Stop> stopPoints = new List<Stop> { stop1, stop2 };

                // Get the route results.
                _routeResult = await _routeTask.SolveRouteAsync(_routeParams);
                _route = _routeResult.Routes[0];

                // Add a graphics overlay for the route graphics.
                MyMapView.GraphicsOverlays.Add(new GraphicsOverlay());

                // Add graphics for the stops.
                SimpleMarkerSymbol stopSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Diamond, Color.OrangeRed, 20);
                MyMapView.GraphicsOverlays[0].Graphics.Add(new Graphic(_conventionCenter, stopSymbol));
                MyMapView.GraphicsOverlays[0].Graphics.Add(new Graphic(_aerospaceMuseum, stopSymbol));

                // Create a graphic (with a dashed line symbol) to represent the route.
                _routeAheadGraphic = new Graphic(_route.RouteGeometry) { Symbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Dash, Color.BlueViolet, 5) };

                // Create a graphic (solid) to represent the route that's been traveled (initially empty).
                _routeTraveledGraphic = new Graphic { Symbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.LightBlue, 3) };

                // Add the route graphics to the map view.

                // Set the map viewpoint to show the entire route.
                await MyMapView.SetViewpointGeometryAsync(_route.RouteGeometry, 100);

                // Enable the navigation button.
                StartNavigationButton.IsEnabled = true;
            catch (Exception e)
                await Application.Current.MainPage.DisplayAlert("Error", e.Message, "OK");

        private async void StartNavigation(object sender, EventArgs e)
            // Disable the start navigation button.
            StartNavigationButton.IsEnabled = false;

            // Get the directions for the route.
            _directionsList = _route.DirectionManeuvers;

            // Create a route tracker.
            _tracker = new RouteTracker(_routeResult, 0);
            _tracker.NewVoiceGuidance += SpeakDirection;

            // Handle route tracking status changes.
            _tracker.TrackingStatusChanged += TrackingStatusUpdated;

            // Check if this route task supports rerouting.
            if (_routeTask.RouteTaskInfo.SupportsRerouting)
                // Enable automatic re-routing.
                await _tracker.EnableReroutingAsync(_routeTask, _routeParams, ReroutingStrategy.ToNextWaypoint, false);

                // Handle re-routing completion to display updated route graphic and report new status.
                _tracker.RerouteStarted += RerouteStarted;
                _tracker.RerouteCompleted += RerouteCompleted;

            // Turn on navigation mode for the map view.
            MyMapView.LocationDisplay.AutoPanMode = LocationDisplayAutoPanMode.Navigation;
            MyMapView.LocationDisplay.AutoPanModeChanged += AutoPanModeChanged;

            // Add a data source for the location display.
            MyMapView.LocationDisplay.DataSource = new RouteTrackerDisplayLocationDataSource(new GpxProvider(_gpxPath), _tracker);
            // Use this instead if you want real location:
            // MyMapView.LocationDisplay.DataSource = new RouteTrackerLocationDataSource(new SystemLocationDataSource(), _tracker);

            // Enable the location display (this will start the location data source).
            MyMapView.LocationDisplay.IsEnabled = true;

        private void RerouteStarted(object sender, EventArgs e)
            // Remove the event listeners for tracking status changes while the route tracker recalculates.
            _tracker.NewVoiceGuidance -= SpeakDirection;
            _tracker.TrackingStatusChanged -= TrackingStatusUpdated;

        private void RerouteCompleted(object sender, RouteTrackerRerouteCompletedEventArgs e)
            // Get the new directions.
            _directionsList = e.TrackingStatus.RouteResult.Routes[0].DirectionManeuvers;

            // Re-add the event listeners for tracking status changes.
            _tracker.NewVoiceGuidance += SpeakDirection;
            _tracker.TrackingStatusChanged += TrackingStatusUpdated;

        private void TrackingStatusUpdated(object sender, RouteTrackerTrackingStatusChangedEventArgs e)
            TrackingStatus status = e.TrackingStatus;

            // Start building a status message for the UI.
            System.Text.StringBuilder statusMessageBuilder = new System.Text.StringBuilder("Route Status:\n");

            // Check if navigation is on route.
            if (status.IsOnRoute && !status.IsRouteCalculating)
                // Check the destination status.
                if (status.DestinationStatus == DestinationStatus.NotReached || status.DestinationStatus == DestinationStatus.Approaching)
                    statusMessageBuilder.AppendLine("Distance remaining: " +
                                                status.RouteProgress.RemainingDistance.DisplayText + " " +

                    statusMessageBuilder.AppendLine("Time remaining: " +

                    if (status.CurrentManeuverIndex + 1 < _directionsList.Count)
                        statusMessageBuilder.AppendLine("Next direction: " + _directionsList[status.CurrentManeuverIndex + 1].DirectionText);

                    // Set geometries for progress and the remaining route.
                    _routeAheadGraphic.Geometry = status.RouteProgress.RemainingGeometry;
                    _routeTraveledGraphic.Geometry = status.RouteProgress.TraversedGeometry;
                else if (status.DestinationStatus == DestinationStatus.Reached)
                    statusMessageBuilder.AppendLine("Destination reached.");

                    // Set the route geometries to reflect the completed route.
                    _routeAheadGraphic.Geometry = null;
                    _routeTraveledGraphic.Geometry = status.RouteResult.Routes[0].RouteGeometry;
                statusMessageBuilder.AppendLine("Off route!");

            Device.BeginInvokeOnMainThread(() =>
                // Show the status information in the UI.
                MessagesTextBlock.Text = statusMessageBuilder.ToString().TrimEnd('\n').TrimEnd('\r');

        private async void SpeakDirection(object sender, RouteTrackerNewVoiceGuidanceEventArgs e)
            // Say the direction using voice synthesis.
            if (e.VoiceGuidance.Text?.Length > 0)
                _speechToken = new CancellationTokenSource();
                await SpeakAsync(e.VoiceGuidance.Text, _speechToken.Token);

        private void AutoPanModeChanged(object sender, LocationDisplayAutoPanMode e)
            // Turn the recenter button on or off when the location display changes to or from navigation mode.
            RecenterButton.IsEnabled = e != LocationDisplayAutoPanMode.Navigation;

        private void RecenterButton_Click(object sender, EventArgs e)
            // Change the mapview to use navigation mode.
            MyMapView.LocationDisplay.AutoPanMode = LocationDisplayAutoPanMode.Navigation;

        public void Dispose()
            // Stop currently playing speech.

            // Stop the tracker.
            if (_tracker != null)
                _tracker.TrackingStatusChanged -= TrackingStatusUpdated;
                _tracker.NewVoiceGuidance -= SpeakDirection;
                _tracker.RerouteStarted -= RerouteStarted;
                _tracker.RerouteCompleted -= RerouteCompleted;
                _tracker = null;

            // Stop the location data source.

    // This location data source uses an input data source and a route tracker.
    // The location source that it updates is based on the snapped-to-route location from the route tracker.
    public class RouteTrackerDisplayLocationDataSource : LocationDataSource
        private LocationDataSource _inputDataSource;
        private RouteTracker _routeTracker;

        public RouteTrackerDisplayLocationDataSource(LocationDataSource dataSource, RouteTracker routeTracker)
            // Set the data source
            _inputDataSource = dataSource ?? throw new ArgumentNullException(nameof(dataSource));

            // Set the route tracker.
            _routeTracker = routeTracker ?? throw new ArgumentNullException(nameof(routeTracker));

            // Change the tracker location when the source location changes.
            _inputDataSource.LocationChanged += InputLocationChanged;

            // Update the location output when the tracker location updates.
            _routeTracker.TrackingStatusChanged += TrackingStatusChanged;

        private void InputLocationChanged(object sender, Location e)
            // Update the tracker location with the new location from the source (simulation or GPS).

        private void TrackingStatusChanged(object sender, RouteTrackerTrackingStatusChangedEventArgs e)
            // Check if the tracking status has a location.
            if (e.TrackingStatus.DisplayLocation != null)
                // Call the base method for LocationDataSource to update the location with the tracked (snapped to route) location.

        protected override Task OnStartAsync() => _inputDataSource.StartAsync();

        protected override Task OnStopAsync() => _inputDataSource.StartAsync();