Use a routing service to navigate between two points.
Use case
Navigation is often used by field workers while traveling between two points to get live directions based on their location.
How to use the sample
Tap 'Start Routing' to simulate traveling and to receive directions from a preset starting point to a preset destination. Tap 'Reset' to start the simulation from the beginning.
How it works
- Create a
RouteTask
using a URL to an online route service. - 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.solveRoute(routeParameters)
to get aRouteResult
. - Create a
RouteTracker
using the route result, and the index of the desired route to take. - Create a
RouteTrackerLocationDataSource
with the route tracker and simulated location data source to snap the location display to the route. - Subscribe to
RouteTracker.onTrackingStatusChanged
and use theTrackingStatus
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. - Subscribe to
RouteTracker.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 it's 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, we 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
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.
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';
class NavigateRoute extends StatefulWidget {
const NavigateRoute({super.key});
@override
State<NavigateRoute> createState() => _NavigateRouteState();
}
class _NavigateRouteState extends State<NavigateRoute> 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;
// Variables for tracking the navigation route.
late RouteTracker _routeTracker;
late RouteResult _routeResult;
late ArcGISRoute _route;
// List of driving directions for the route.
final _directionsList = <DirectionManeuver>[];
// Third-party plugin for text-to-speech.
final _flutterTts = FlutterTts();
// Create a simulated location data source from the route geometry.
final _simulatedLocationDataSource = SimulatedLocationDataSource();
// Graphics to show progress along the route.
late Graphic _routeAheadGraphic;
late Graphic _routeTraveledGraphic;
// GraphicsOverlay for route graphics
final _routeGraphicsOverlay = GraphicsOverlay();
// A flag to indicate if the destination is reached.
var _destinationReached = false;
// ValueNotifier for status text.
final _statusTextNotifier = ValueNotifier('Directions are shown here.');
// Track Speech Engine Status.
var _speechEngineReady = true;
// San Diego Convention Center.
final _conventionCenter = ArcGISPoint(
x: -117.160386727,
y: 32.706608,
spatialReference: SpatialReference.wgs84,
);
// USS San Diego Memorial.
final _memorial = ArcGISPoint(
x: -117.173034,
y: 32.712327,
spatialReference: SpatialReference.wgs84,
);
// RH Fleet Aerospace Museum.
final _aerospaceMuseum = ArcGISPoint(
x: -117.147230,
y: 32.730467,
spatialReference: SpatialReference.wgs84,
);
// Feature service URI for routing in San Diego.
final _routingUri = Uri.parse(
'https://sampleserver7.arcgisonline.com/server/rest/services/NetworkAnalysis/SanDiego/NAServer/Route',
);
// Listener to track changes in autoPanMode.
StreamSubscription<LocationDisplayAutoPanMode>? _autoPanModeSubscription;
@override
void initState() {
super.initState();
// Listen to the onAutoPanModeChanged stream.
_autoPanModeSubscription = _mapViewController
.locationDisplay
.onAutoPanModeChanged
.listen((autoPanMode) {
setState(() {});
});
}
@override
void dispose() {
_simulatedLocationDataSource.stop();
_autoPanModeSubscription?.cancel();
_flutterTts.stop();
super.dispose();
}
@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: [
// A button to start navigation.
ElevatedButton(
onPressed: _destinationReached ? null : toggleRouting,
child: Text(
_mapViewController.locationDisplay.started
? 'Stop Routing'
: 'Start Routing',
),
),
// A button to recenter the map.
ElevatedButton(
// Gets activated only when the focus changes from navigation.
onPressed:
_mapViewController.locationDisplay.autoPanMode ==
LocationDisplayAutoPanMode.navigation
? null
: recenter,
child: const Text('Recenter'),
),
// A button to reset navigation.
ElevatedButton(
onPressed: resetNavigation,
child: const Text('Reset'),
),
],
),
],
),
// Display a progress indicator and prevent interaction until state is ready.
LoadingIndicator(visible: !_ready),
// Display a banner with the current status at the top.
SafeArea(
child: IgnorePointer(
child: Container(
padding: const EdgeInsets.all(10),
color: Colors.white.withValues(alpha: 0.7),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Expanded(
child: ValueListenableBuilder(
valueListenable: _statusTextNotifier,
builder: (context, statusText, child) {
return Text(
statusText,
softWrap: true,
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.labelMedium,
);
},
),
),
],
),
),
),
),
],
),
),
);
}
Future<void> onMapViewReady() async {
// Create a map with a navigation basemap style.
final map = ArcGISMap.withBasemapStyle(BasemapStyle.arcGISNavigation);
_mapViewController.arcGISMap = map;
// Add the graphics overlay to the map view.
_mapViewController.graphicsOverlays.add(_routeGraphicsOverlay);
// Solve the route.
await solveRoute();
// Initialize Flutter TTS.
await initFlutterTts();
// Set the initial viewpoint to encompass the route geometry.
setInitialViewpoint();
// Set the ready state variable to true to enable the sample UI.
setState(() => _ready = true);
}
Future<void> initFlutterTts() async {
// Detect the user's locale.
final locale = Localizations.localeOf(context).toLanguageTag();
// 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,
);
}
}
void setInitialViewpoint() {
// Set the initial viewpoint to encompass the route geometry.
final routeGeometry = _route.routeGeometry;
if (routeGeometry != null) {
final viewpoint = Viewpoint.fromTargetExtent(routeGeometry);
_mapViewController.setViewpoint(viewpoint);
}
}
Future<void> solveRoute() async {
// Create a route with the routing URI.
final routeTask = RouteTask.withUri(_routingUri);
// Create default parameters for the route task.
final parameters = await _createRouteParameters(routeTask);
await _solveRouteAndSetGraphics(routeTask, parameters);
}
Future<RouteParameters> _createRouteParameters(RouteTask routeTask) async {
// Create default parameters for the route task.
final parameters = await routeTask.createDefaultParameters();
// Set stops for the route.
parameters.setStops([
Stop(_conventionCenter),
Stop(_memorial),
Stop(_aerospaceMuseum),
]);
// Configure the parameters.
parameters.returnDirections = true;
parameters.returnStops = true;
parameters.returnRoutes = true;
parameters.outputSpatialReference = SpatialReference.wgs84;
return parameters;
}
Future<void> _solveRouteAndSetGraphics(
RouteTask routeTask,
RouteParameters parameters,
) async {
// Solve the route and get the result.
_routeResult = await routeTask.solveRoute(parameters);
_route = _routeResult.routes.first;
_directionsList.addAll(_route.directionManeuvers);
// Create graphics for the route ahead and traveled.
_routeAheadGraphic = Graphic(
geometry: _route.routeGeometry,
symbol: SimpleLineSymbol(
style: SimpleLineSymbolStyle.dash,
color: Colors.purple,
width: 5,
),
);
_routeTraveledGraphic = Graphic(
symbol: SimpleLineSymbol(color: Colors.blue, width: 3),
);
// Add the route graphics to the overlay.
_routeGraphicsOverlay.graphics.add(_routeAheadGraphic);
_routeGraphicsOverlay.graphics.add(_routeTraveledGraphic);
}
Future<void> toggleRouting() async {
setState(() => _ready = false);
if (_mapViewController.locationDisplay.started) {
_mapViewController.locationDisplay.stop();
} else {
await _initializeSimulatedLocationDataSource();
await _createAndConfigureRouteTracker();
await _startLocationDisplay();
}
setState(() => _ready = true);
}
Future<void> _initializeSimulatedLocationDataSource() async {
// Set locations with polyline for the simulated location data source.
_simulatedLocationDataSource.setLocationsWithPolyline(
_route.routeGeometry!,
simulationParameters: SimulationParameters(
startTime: DateTime.now(),
horizontalAccuracy: 5,
verticalAccuracy: 5,
speed: 35,
),
);
}
Future<void> _createAndConfigureRouteTracker() async {
// Create a route tracker with the route result.
_routeTracker =
RouteTracker.create(
routeResult: _routeResult,
routeIndex: 0,
skipCoincidentStops: true,
)!;
_routeTracker.voiceGuidanceUnitSystem = UnitSystem.imperial;
// Set the speech engine ready callback.
_routeTracker.setSpeechEngineReady(() => _speechEngineReady);
// Listen for tracking status updates.
_routeTracker.onTrackingStatusChanged.listen((status) async {
_updateRouteGraphics(status);
_updateStatusText(status);
// Handle destination status changes.
if (status.destinationStatus == DestinationStatus.reached) {
if (status.remainingDestinationCount > 1) {
await _routeTracker.switchToNextDestination();
} else {
await _simulatedLocationDataSource.stop();
setState(() => _destinationReached = true);
}
}
});
// Listen for voice guidance updates.
_routeTracker.onNewVoiceGuidance.listen((voiceGuidance) async {
_speechEngineReady = false;
await _flutterTts.speak(voiceGuidance.text);
_speechEngineReady = true;
});
}
Future<void> _startLocationDisplay() async {
// Start the simulated location data source.
await _simulatedLocationDataSource.start();
// Create a RouteTrackerLocationDataSource.
final routeTrackerLocationSource = RouteTrackerLocationDataSource(
routeTracker: _routeTracker,
locationDataSource: _simulatedLocationDataSource,
);
// Set the location display data source.
_mapViewController.locationDisplay.dataSource = routeTrackerLocationSource;
// Set the auto-pan mode for the location display.
_mapViewController.locationDisplay.autoPanMode =
LocationDisplayAutoPanMode.navigation;
// Start the location display.
_mapViewController.locationDisplay.start();
}
void _updateRouteGraphics(TrackingStatus status) {
// Update the graphics for the route traveled and ahead.
_routeTraveledGraphic.geometry = status.routeProgress.traversedGeometry;
_routeAheadGraphic.geometry = status.routeProgress.remainingGeometry;
}
String formatDuration(Duration duration) {
final hours = duration.inHours;
final minutes = duration.inMinutes.remainder(60);
final seconds = duration.inSeconds.remainder(60);
if (hours > 0) {
return '$hours Hours, $minutes Minutes, and $seconds Seconds';
} else if (minutes > 0) {
return '$minutes Minutes and $seconds Seconds';
} else {
return '$seconds Seconds';
}
}
void _updateStatusText(TrackingStatus status) {
// Updates the status text displayed to the user with the current navigation information.
final remainingTimeInSeconds = status.routeProgress.remainingTime * 60;
final formattedTime = formatDuration(
Duration(seconds: remainingTimeInSeconds.toInt()),
);
_statusTextNotifier.value = '''
Distance remaining: ${status.routeProgress.remainingDistance.displayText} ${status.routeProgress.remainingDistance.displayTextUnits.abbreviation}
Time remaining: $formattedTime
Next direction: ${_directionsList[status.currentManeuverIndex + 1].directionText}
''';
}
void recenter() {
_mapViewController.locationDisplay.autoPanMode =
LocationDisplayAutoPanMode.navigation;
}
// Reset the navigation state.
Future<void> resetNavigation() async {
setState(() => _ready = false);
// Stop the location display.
_mapViewController.locationDisplay.stop();
// Solve the route again.
await solveRoute();
// Clear the existing graphics.
_routeGraphicsOverlay.graphics.clear();
// Add the new route graphics to the overlay.
_routeGraphicsOverlay.graphics.add(_routeAheadGraphic);
_routeGraphicsOverlay.graphics.add(_routeTraveledGraphic);
// Stop any ongoing speech.
await _flutterTts.stop();
// Reset the status text.
_statusTextNotifier.value = 'Directions are shown here.';
// Set the viewpoint to encompass the route geometry.
setInitialViewpoint();
// Update the state to reflect the reset.
setState(() => _ready = true);
}
}