Navigate route with rerouting

View 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 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

  1. Create a RouteTask using the downloaded Geodatabase.
  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.solve(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 RouteTracker.enableRerouting(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 the present location to the next waypoint or stop.
  8. Use RouteTrackerLocationDataSource to track the location of the device and update the route tracking status.
  9. Add a listener to capture onTrackingStatusChanged, 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 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.
  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 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

navigate_route_with_rerouting.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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
// 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';
}

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