Navigate route

View on GitHub

Use a routing service to navigate between two points.

Image of navigate route

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

  1. Create a RouteTask using a URL to an online route service.
  2. Generate default RouteParameters using routeTask.createDefaultParameters().
  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.solveRoute(routeParameters) to get a RouteResult.
  6. Create a RouteTracker using the route result, and the index of the desired route to take.
  7. Create a RouteTrackerLocationDataSource with the route tracker and simulated location data source to snap the location display to the route.
  8. Subscribe to RouteTracker.onTrackingStatusChanged and use the TrackingStatus 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.
  9. Subscribe to RouteTracker.onNewVoiceGuidance 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.
  10. You can also query the tracking status for the current DirectionManeuver index, retrieve that maneuver from the Route and get it's direction text to display in the GUI.
  11. 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, 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

navigate_route.dart
Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
// 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);
  }
}

Your browser is no longer supported. Please upgrade your browser for the best experience. See our browser deprecation post for more details.