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
Tap the play button to simulate travel and receive directions from a preset starting point to a preset destination. Observe how the route is recalculated if the simulation deviates from the suggested path. You should hear voice directions when maneuver instructions are available. You can stop or restart the simulated movement and recenter the navigation.
How it works
- Create a
RouteTask
using the downloadedGeodatabase
. - Generate default
RouteParameters
usingrouteTask.createDefaultParameters()
. - Set
returnStops
andreturnDirections
on the parameters to true. - Add
Stop
s to the parametersstops
collection for each destination. - Solve the route using
routeTask.solve(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
RouteTracker.enableRerouting(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 the present location to the next waypoint or stop. - Use
RouteTrackerLocationDataSource
to track the location of the device and update the route tracking status. - Add a listener to capture
onTrackingStatusChanged
, 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
onNewVoiceGuidance
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 JSON file provides a simulated path for the device to demonstrate routing while traveling.
Link |
---|
Navigate a Route JSON Track |
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 2025 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
//
// https://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.
//
import 'dart:async';
import 'dart:io';
import 'package:arcgis_maps/arcgis_maps.dart';
import 'package:arcgis_maps_sdk_flutter_samples/common/common.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_tts/flutter_tts.dart';
import 'package:path_provider/path_provider.dart';
class NavigateRouteWithRerouting extends StatefulWidget {
const NavigateRouteWithRerouting({super.key});
@override
State<NavigateRouteWithRerouting> createState() =>
_NavigateRouteWithReroutingState();
}
class _NavigateRouteWithReroutingState extends State<NavigateRouteWithRerouting>
with SampleStateSupport {
// Create a controller for the map view.
final _mapViewController = ArcGISMapView.createController();
// A flag for when the map view is ready and controls can be used.
var _ready = false;
// A text-to-speech plugin to provide voice guidance.
late FlutterTts _flutterTts;
// A RouteTask to solve the route.
late RouteTask _routeTask;
// A RouteTracker to track the route.
late RouteTracker _routeTracker;
// A RouteResult to store the route result.
late RouteResult _routeResult;
// Rerouting parameters to enable rerouting.
late ReroutingParameters _reroutingParameters;
// A SimulatedLocationDataSource to simulate the location data source.
SimulatedLocationDataSource? _simulatedLocationDataSource;
// Graphics to show progress on the route.
late Graphic _remainingRouteGraphic;
late Graphic _routeTraveledGraphic;
// A PolylineBuilder to store the traversed route.
var _traversedRouteBuilder = PolylineBuilder(
spatialReference: SpatialReference.wgs84,
);
// San Diego Convention Center.
final _startPoint = ArcGISPoint(
x: -117.160386727,
y: 32.706608,
spatialReference: SpatialReference.wgs84,
);
// RH Fleet Aerospace Museum.
final _endPoint = ArcGISPoint(
x: -117.146679,
y: 32.730351,
spatialReference: SpatialReference.wgs84,
);
// Indicate whether the route is being navigated.
var _isNavigating = false;
var _resetToNavigationMode = false;
var _reset = false;
var _setupDataAndInitNavigation = false;
// Variables to show the remaining distance, time, and next direction.
var _routeStatus = '';
var _remainingDistance = '';
var _remainingTime = '';
var _nextDirection = '';
// Future to download the geodatabase.
late Future<String> _geodatabasePathFuture;
// Future to download the simulated location data source.
late Future<SimulatedLocationDataSource> _simulatedLocationDataSourceFuture;
// Stream subscriptions
StreamSubscription<VoiceGuidance>? _voiceGuidanceSubscription;
StreamSubscription<TrackingStatus>? _trackingStatusSubscription;
StreamSubscription<void>? _rerouteStartedSubscription;
StreamSubscription<void>? _rerouteCompletedSubscription;
StreamSubscription<LocationDisplayAutoPanMode>?
_autoPanModeChangedSubscription;
StreamSubscription<LoadStatus>? _mapLoadingSubscription;
@override
void initState() {
// Downloads the San Diego geodatabase required for offline routing in San Diego.
_geodatabasePathFuture = downloadSanDiegoGeodatabase();
// Downloads the data source's locations using a local JSON file.
_simulatedLocationDataSourceFuture = getLocationDataSource();
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
top: false,
left: false,
right: false,
child: Stack(
children: [
Column(
children: [
Expanded(
// Add a map view to the widget tree and set a controller.
child: ArcGISMapView(
controllerProvider: () => _mapViewController,
onMapViewReady: onMapViewReady,
),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Container(
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Theme.of(context).primaryColorLight,
),
// Add a button to reset navigation if it has started.
child: IconButton(
onPressed: _reset ? reset : null,
color: Colors.white,
icon: const Icon(Icons.restore),
),
),
Container(
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Theme.of(context).primaryColorLight,
),
// Add a button to start/stop navigation.
child: IconButton(
onPressed:
_setupDataAndInitNavigation
? null
: (_isNavigating ? stop : start),
color: Colors.white,
icon:
_isNavigating
? const Icon(Icons.stop)
: const Icon(Icons.play_arrow),
),
),
Container(
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Theme.of(context).primaryColorLight,
),
// Add a button to reset location display to navigation mode.
child: IconButton(
onPressed:
_resetToNavigationMode
? resetToNavigationMode
: null,
color: Colors.white,
icon: const Icon(Icons.navigation),
),
),
],
),
Padding(
padding: const EdgeInsets.fromLTRB(10, 8, 8, 8),
child: Row(
children: [
Expanded(
child: Text(
'Route status: $_routeStatus',
style: Theme.of(context).textTheme.labelMedium,
),
),
],
),
),
Padding(
padding: const EdgeInsets.fromLTRB(10, 0, 8, 8),
child: Row(
children: [
Expanded(
child: Text(
'Distance remaining: $_remainingDistance',
style: Theme.of(context).textTheme.labelMedium,
),
),
],
),
),
Padding(
padding: const EdgeInsets.fromLTRB(10, 0, 8, 8),
child: Row(
children: [
Expanded(
child: Text(
'Time remaining: $_remainingTime',
style: Theme.of(context).textTheme.labelMedium,
),
),
],
),
),
Padding(
padding: const EdgeInsets.fromLTRB(10, 0, 8, 24),
child: Row(
children: [
Expanded(
child: Text(
'Next direction: $_nextDirection',
style: Theme.of(context).textTheme.labelMedium,
softWrap: true,
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
),
],
),
),
],
),
// Display a progress indicator and prevent interaction until state is ready.
LoadingIndicator(visible: !_ready),
// Display a progress indicator while the navigation data is loading.
Visibility(
visible: _setupDataAndInitNavigation,
child: const Center(
child: SizedBox(
width: 300,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
LinearProgressIndicator(),
Text('Downloading data...'),
],
),
),
),
),
],
),
),
);
}
@override
void dispose() {
_flutterTts.stop();
_simulatedLocationDataSource?.stop();
_voiceGuidanceSubscription?.cancel();
_trackingStatusSubscription?.cancel();
_rerouteStartedSubscription?.cancel();
_rerouteCompletedSubscription?.cancel();
_autoPanModeChangedSubscription?.cancel();
_mapLoadingSubscription?.cancel();
super.dispose();
}
// Set up the map with a navigation basemap style.
Future<void> onMapViewReady() async {
// Create a map with a navigation basemap style.
final map = ArcGISMap.withBasemapStyle(BasemapStyle.arcGISNavigation);
_mapViewController.arcGISMap = map;
_mapLoadingSubscription = map.onLoadStatusChanged.listen((
loadStatus,
) async {
if (loadStatus == LoadStatus.loaded) {
setState(() => _setupDataAndInitNavigation = true);
await initRouteTask();
setState(() => _setupDataAndInitNavigation = false);
}
});
// Initialize FlutterTts.
await initFlutterTts();
setState(() => _ready = true);
}
// Initialize the FlutterTts plugin.
Future<void> initFlutterTts() async {
// Detect the user's locale.
final locale = Localizations.localeOf(context).toLanguageTag();
_flutterTts = FlutterTts();
// Set the language based on the user's locale.
await _flutterTts.setLanguage(locale);
await _flutterTts.setSpeechRate(0.5);
await _flutterTts.setVolume(1);
await _flutterTts.setPitch(1.3);
// Check if platform is iOS.
final isIOS = !kIsWeb && Platform.isIOS;
if (isIOS) {
await _flutterTts.setIosAudioCategory(
IosTextToSpeechAudioCategory.playback,
[
IosTextToSpeechAudioCategoryOptions.allowBluetooth,
IosTextToSpeechAudioCategoryOptions.allowBluetoothA2DP,
IosTextToSpeechAudioCategoryOptions.mixWithOthers,
],
IosTextToSpeechAudioMode.voicePrompt,
);
}
}
// Initialize the route task, route parameters, and route result.
Future<void> initRouteTask() async {
// Get the path to the geodatabase.
final geodatabasePath = await _geodatabasePathFuture;
// Create a route task.
_routeTask = RouteTask.withGeodatabase(
pathToDatabase: Uri.file(geodatabasePath),
networkName: 'Streets_ND',
);
// Create route parameters.
final routeParameters =
await _routeTask.createDefaultParameters()
..returnDirections = true
..returnStops = true
..returnRoutes = true
..outputSpatialReference = SpatialReference.wgs84;
// Sets the start and destination stops for the route.
routeParameters.setStops([
Stop(_startPoint)..name = 'San Diego Convention Center',
Stop(_endPoint)..name = 'RH Fleet Aerospace Museum',
]);
// Solve the route and store the result.
_routeResult = await _routeTask.solveRoute(routeParameters);
// Initializes and adds graphics to the map view to visually represent the route,
// including the remaining route, traveled route, and start/end points.
initRouteGraphics();
// Create Rerouting parameters with the route task and parameters.
_reroutingParameters =
ReroutingParameters.create(
routeTask: _routeTask,
routeParameters: routeParameters,
)!
..strategy = ReroutingStrategy.toNextWaypoint
..visitFirstStopOnStart = false;
// Initialize the route tracker, location display, and route graphics.
await initNavigation();
}
// Initialize the route tracker, location display, and route graphics.
Future<void> initNavigation() async {
// Create the route tracker with rerouting enabled.
_routeTracker =
RouteTracker.create(
routeResult: _routeResult,
routeIndex: 0,
skipCoincidentStops: true,
)!;
// Enable rerouting on the route tracker.
if (_routeTask.getRouteTaskInfo().supportsRerouting) {
await _routeTracker.enableRerouting(parameters: _reroutingParameters);
} else {
showMessageDialog('Rerouting is not supported.');
}
// Get the simulated location data source.
_simulatedLocationDataSource = await _simulatedLocationDataSourceFuture;
// Create a route tracker location data source to snap the location display to the route.
final routeTrackerLocationDataSource = RouteTrackerLocationDataSource(
routeTracker: _routeTracker,
locationDataSource: _simulatedLocationDataSource,
);
// Set the location data source.
_mapViewController.locationDisplay.dataSource =
routeTrackerLocationDataSource;
_mapViewController.locationDisplay.autoPanMode =
LocationDisplayAutoPanMode.navigation;
_autoPanModeChangedSubscription = _mapViewController
.locationDisplay
.onAutoPanModeChanged
.listen((event) {
if (event != LocationDisplayAutoPanMode.navigation) {
setState(() => _resetToNavigationMode = true);
} else {
setState(() => _resetToNavigationMode = false);
}
});
// Update the remaining route graphic and center the map view on the route.
await zoomToRoute();
// Set the route tracker locale.
_routeTracker.voiceGuidanceUnitSystem =
const Locale.fromSubtags().languageCode == 'en'
? UnitSystem.imperial
: UnitSystem.metric;
// Listen for voice guidance and tracking status changes.
_voiceGuidanceSubscription = _routeTracker.onNewVoiceGuidance.listen(
updateGuidance,
);
_trackingStatusSubscription = _routeTracker.onTrackingStatusChanged.listen(
updateProgress,
);
_rerouteStartedSubscription = _routeTracker.onRerouteStarted.listen((_) {
_flutterTts.speak('Rerouting');
setState(() => _routeStatus = 'Rerouting');
});
_rerouteCompletedSubscription = _routeTracker.onRerouteCompleted.listen((
_,
) {
setState(() => _routeStatus = 'Reroute completed');
});
}
// Speak the voice guidance.
void updateGuidance(VoiceGuidance voiceGuidance) {
final nextDirection = voiceGuidance.text;
if (nextDirection.isEmpty) return;
_routeTracker.setSpeechEngineReady(() => false);
_flutterTts.speak(nextDirection).then((value) {
_routeTracker.setSpeechEngineReady(() => true);
});
}
// Listen for tracking status changes and update the route status.
Future<void> updateProgress(TrackingStatus status) async {
// Update the route graphics.
_remainingRouteGraphic.geometry = status.routeProgress.remainingGeometry;
final currentPosition =
_mapViewController.locationDisplay.location?.position;
if (currentPosition != null) {
_traversedRouteBuilder.addPoint(currentPosition);
_routeTraveledGraphic.geometry = _traversedRouteBuilder.toGeometry();
}
// Update the status message.
switch (status.destinationStatus) {
case DestinationStatus.approaching:
case DestinationStatus.notReached:
// Format the route's remaining distance and time.
final distanceRemainingText =
status.routeProgress.remainingDistance.displayText;
final displayUnit =
status
.routeProgress
.remainingDistance
.displayTextUnits
.abbreviation;
final remainingTimeInSeconds = status.routeProgress.remainingTime * 60;
final timeRemainingText = formatDuration(
remainingTimeInSeconds.toInt(),
);
// Get the next direction from the route's direction maneuvers.
var nextDirection = '';
final directionManeuvers =
status.routeResult.routes.first.directionManeuvers;
final nextManeuverIndex = status.currentManeuverIndex + 1;
if (nextManeuverIndex < directionManeuvers.length) {
nextDirection = directionManeuvers[nextManeuverIndex].directionText;
}
setState(() {
_routeStatus = '${status.destinationStatus}';
_remainingDistance = '$distanceRemainingText $displayUnit';
_remainingTime = timeRemainingText;
_nextDirection = nextDirection;
});
case DestinationStatus.reached:
if (status.remainingDestinationCount > 1) {
setState(() {
_routeStatus = 'Intermediate stop reached, continue to next stop.';
});
await _routeTracker.switchToNextDestination();
} else {
await stop();
await reset();
setState(() {
_routeStatus = 'Destination reached.';
});
}
}
}
// Zoom to the route.
Future<void> zoomToRoute() async {
final routeLine = _routeResult.routes.first.routeGeometry;
_remainingRouteGraphic.geometry = routeLine;
await _mapViewController.setViewpointCenter(
routeLine!.extent.center,
scale: 25000,
);
await _mapViewController.setViewpointRotation(angleDegrees: 0);
}
// Start the navigation.
Future<void> start() async {
_mapViewController.locationDisplay.autoPanMode =
LocationDisplayAutoPanMode.navigation;
await _mapViewController.locationDisplay.dataSource.start();
setState(() {
_isNavigating = true;
_reset = true;
});
}
// Reset the LocationDisplay to the navigation mode.
void resetToNavigationMode() {
_mapViewController.locationDisplay.autoPanMode =
LocationDisplayAutoPanMode.navigation;
}
// Stop the navigation.
Future<void> stop() async {
await _flutterTts.stop();
// Stop the location display.
_mapViewController.locationDisplay.autoPanMode =
LocationDisplayAutoPanMode.off;
await _mapViewController.locationDisplay.dataSource.stop();
setState(() {
_isNavigating = false;
_resetToNavigationMode = false;
});
}
// Reset the navigation to begin again.
Future<void> reset() async {
await stop();
_traversedRouteBuilder = PolylineBuilder(
spatialReference: SpatialReference.wgs84,
);
setState(() {
_routeStatus = '';
_remainingDistance = '';
_remainingTime = '';
_nextDirection = '';
_reset = false;
});
_simulatedLocationDataSource!.currentLocationIndex = 0;
await initNavigation();
_routeTraveledGraphic.geometry = null;
_remainingRouteGraphic.geometry = _routeResult.routes.first.routeGeometry;
}
// Create a simulated location data source.
Future<SimulatedLocationDataSource> getLocationDataSource() async {
// Load the route point JSON file.
final tourJsonPath = await downloadSanDiegoTourPath();
final jsonString = await File(tourJsonPath).readAsString();
final routeLine = Geometry.fromJsonString(jsonString) as Polyline;
final simulatedLocationDataSource =
SimulatedLocationDataSource()..setLocationsWithPolyline(
routeLine,
simulationParameters: SimulationParameters(
startTime: DateTime.now(),
horizontalAccuracy: 5,
verticalAccuracy: 5,
),
);
return simulatedLocationDataSource;
}
// Set up the route graphics.
void initRouteGraphics() {
_mapViewController.graphicsOverlays.clear();
_mapViewController.graphicsOverlays.add(GraphicsOverlay());
_remainingRouteGraphic = Graphic(
symbol: SimpleLineSymbol(
style: SimpleLineSymbolStyle.dash,
color: Colors.purple,
width: 5,
),
);
_routeTraveledGraphic = Graphic(
symbol: SimpleLineSymbol(color: Colors.blue, width: 3),
);
// Create symbols to use for the start and end stops of the route.
final routeStartCircleSymbol = SimpleMarkerSymbol(
color: Colors.blue,
size: 15,
);
final routeEndCircleSymbol = SimpleMarkerSymbol(
color: Colors.blue,
size: 15,
);
final routeStartNumberSymbol = TextSymbol(
text: 'A',
color: Colors.white,
size: 10,
);
final routeEndNumberSymbol = TextSymbol(
text: 'B',
color: Colors.white,
size: 10,
);
_mapViewController.graphicsOverlays.first.graphics.addAll([
_remainingRouteGraphic,
_routeTraveledGraphic,
Graphic(geometry: _startPoint, symbol: routeStartCircleSymbol)
..zIndex = 100,
Graphic(geometry: _endPoint, symbol: routeEndCircleSymbol)..zIndex = 100,
Graphic(geometry: _startPoint, symbol: routeStartNumberSymbol)
..zIndex = 100,
Graphic(geometry: _endPoint, symbol: routeEndNumberSymbol)..zIndex = 100,
]);
}
// Download the San Diego geodatabase.
Future<String> downloadSanDiegoGeodatabase() async {
// Download the sample data.
await downloadSampleData(['df193653ed39449195af0c9725701dca']);
// Get the application documents directory.
final appDir = await getApplicationDocumentsDirectory();
// Create a file to the geodatabase.
final geodatabaseFile = File(
'${appDir.absolute.path}/san_diego_offline_routing/sandiego.geodatabase',
);
// Return the path to the geodatabase.
return geodatabaseFile.path;
}
// Download San Diego tour path.
Future<String> downloadSanDiegoTourPath() async {
// Download the tour path.
await downloadSampleData(['4caec8c55ea2463982f1af7d9611b8d5']);
// Get the application documents directory.
final appDir = await getApplicationDocumentsDirectory();
// Create the SanDiegoTourPath.json file.
final tourPathFile = File(
'${appDir.absolute.path}/SanDiegoTourPath.json/SanDiegoTourPath.json',
);
// Return the path of the JSON file.
return tourPathFile.path;
}
}
String formatDuration(int seconds) {
final duration = Duration(seconds: seconds);
final hours = duration.inHours.toString().padLeft(2, '0');
final minutes = (duration.inMinutes % 60).toString().padLeft(2, '0');
final secs = (duration.inSeconds % 60).toString().padLeft(2, '0');
return '$hours:$minutes:$secs';
}