Navigate between two points and dynamically recalculate an alternate route when the original route is unavailable.
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
Click '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. Click 'Recenter' to refocus on the location display.
How it works
- Create a
RouteTask
using a URL to an online route service. - Generate default
RouteParameters
usingRouteTask.CreateDefaultParametersAsync()
. - Set
ReturnStops
andReturnDirections
on the parameters to true. - Add
Stop
s to the parametersstops
collection for each destination. - Solve the route using
RouteTask.SolveRouteAsync(routeParameters)
to get aRouteResult
. - Create a
RouteTracker
using the route result, and the index of the desired route to take. - Enable rerouting in the route tracker with
.EnableReroutingAsync(RouteTask, RouteParameters, ReroutingStrategy, false)
. The Boolean specifiesvisitFirstStopOnStart
and is false by default. UseReroutingStrategy.ToNextWaypoint
to specify that in the case of a reroute the new route goes from present location to next waypoint or stop. - Use
.TrackLocationAsync(LocationDataSource.Location)
to track the location of the device and update the route tracking status. - Add a listener to capture
TrackingStatusChangedEvent
, and then get theTrackingStatus
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 aPolyline
), or the remaining time (Double
), amongst others. - Add a
NewVoiceGuidanceListener
to get theVoiceGuidance
whenever new instructions are available. From the voice guidance, get thestring
representing the directions and use a text-to-speech engine to output the maneuver directions. - You can also query the tracking status for the current
DirectionManeuver
index, retrieve that maneuver from theRoute
and get its direction text to display in the GUI. - To establish whether the destination has been reached, get the
DestinationStatus
from the tracking status. If the destination status isReached
, and theRemainingDestinationCount
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.
Tags
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: 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 Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Location;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Timers;
using System.Xml;
namespace ArcGIS.UWP.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.
ReadLocations(gpxFilePath);
// 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;
return;
}
// 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.
_nodeIndex++;
}
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();
gpxDoc.Load(gpx);
XmlNamespaceManager namespaceManager = new XmlNamespaceManager(gpxDoc.NameTable);
// Get the schema information for GPX.
namespaceManager.AddNamespace("x", "http://www.topografix.com/GPX/1/1");
// 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));
}
}
}
}