# Turn-by-turn navigation

> Canonical URL: https://docs.mountaya.com/en/sdks/dart/navigation/
> Last updated: 2026-11-27
> Rules for agents: https://docs.mountaya.com/llms.txt#rules-for-agents

Read an itinerary as a route, follow it with RouteFollowingEngine or DeviceNavigationEngine, speak each maneuver, show progress, and replay a route in Flutter.

Navigation follows a route, tells where the traveller stands, and says each maneuver aloud. The machine is pure Dart in `mountaya_geo`; `mountaya_navigation_flutter` adds the device's location and voice.

## Read the route

`readItineraryRoute` joins a saved itinerary's segments into the one route a traveller follows:

```dart
import 'package:mountaya_client/mountaya_client.dart';
import 'package:mountaya_geo/mountaya_geo.dart';

const publishableKey = String.fromEnvironment('MOUNTAYA_PUBLISHABLE_KEY');

final mountaya = Mountaya(credential: .publishable(key: publishableKey));
final read = await mountaya.studio.itineraries.getItinerary(
  itinerary_id: '0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21',
);
final route =
    readItineraryRoute(read.data.segments, waypoints: read.data.waypoints) ??
    (throw StateError('The itinerary holds no line to follow.'));
print('${route.line.length} positions, ${route.steps.length} steps');
await mountaya.close();
```

- `readItineraryRoute(segments, {required waypoints})` answers a `NavigationRoute` (`line`, `steps`, `duration`), or `null` where the itinerary holds no line. It joins the segments in their chain order, each by its own steps, the lines laid end to end.
- A traveller arrives only where the last segment ends; every arrival before it is a `waypointManeuver` step, named by the itinerary's waypoint standing within 60 m of where its segment ends (`NavigationInstructionKey.waypoint`, its `name` the waypoint's), or `waypointPlain` where no named waypoint stands there.
- A Data API route reads the same way: `readDirectionsSteps(route.steps, coordinateCount: coordinates.length)` answers a `NavigationStepsReading` (`steps`, `refused`) for `mountaya.data.directions`, and `NavigationRoute(line:, steps:, duration:)` holds it.

## Follow the route

`RouteFollowingEngine` follows a route on the positions you hand it, on a server or in a test:

```dart
import 'package:mountaya_client/mountaya_client.dart';
import 'package:mountaya_geo/mountaya_geo.dart';

const publishableKey = String.fromEnvironment('MOUNTAYA_PUBLISHABLE_KEY');

final mountaya = Mountaya(credential: .publishable(key: publishableKey));
final navigation = RouteFollowingEngine<String>(
  // Your route source: the saved itinerary of each id, read as one route.
  route: (itineraryId, signal) async {
    final read = await mountaya.studio.itineraries.getItinerary(
      itinerary_id: itineraryId,
      options: RequestOptions(signal: signal),
    );
    return readItineraryRoute(read.data.segments, waypoints: read.data.waypoints) ??
        (throw StateError('The itinerary holds no line to follow.'));
  },
);
navigation.start('0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21');
await navigation.subscribe().firstWhere((state) => state.route != null);

// Each position you read, [longitude, latitude]: here, Chamonix.
navigation.setPosition([6.8712, 45.9231]);
print(navigation.state.status);
navigation.close();
await mountaya.close();
```

In a Flutter app, `DeviceNavigationEngine` is the same machine with the device's location and voice beside it.

- `RouteFollowingEngine<Request>({required Future<NavigationRoute> Function(Request, AbortSignal) route, onChanged})` and `DeviceNavigationEngine<Request>({required route, LocationSource location = const InertLocationSource(), NavigationVoice voice = const InertNavigationVoice()})` both implement `NavigationEngine<Request>`: `start(request)`, `reroute(request)`, `setPosition(position)`, `stop()`, `close()`, `state`, `subscribe()`.
- `NavigationStatus`: `idle`, `routing`, `navigating`, `offRoute`, `rerouting`, `arrived`, `failed`. A traveller more than 50 m from the route (`offRouteMeters`) is `offRoute`; a new route is asked for by `reroute` alone, never retried. The arrival is raised where a position on the route leaves its progress at the end, so a traveller who stops short never arrives.
- One route request is in flight at a time, handed an `AbortSignal` that a stop or a close aborts. A request that fails leaves the engine `failed` with `state.error` a `NavigationError` (`RouteFailedNavigationError`, `EmptyRouteNavigationError`).
- The engine reads no clock: a position is judged by where it is. Each command has its effect before it returns, and a route's answer is acted on in a later microtask.
- The engine is closed by whoever made it, and closes no location source or voice it was handed.

## Use the device's location

`DeviceLocationSource` reads the device's satellite position while your app holds location access:

```dart
import 'package:mountaya_client/mountaya_client.dart';
import 'package:mountaya_geo/mountaya_geo.dart';
import 'package:mountaya_navigation_flutter/mountaya_navigation_flutter.dart';

const publishableKey = String.fromEnvironment('MOUNTAYA_PUBLISHABLE_KEY');

final mountaya = Mountaya(credential: .publishable(key: publishableKey));
final location = DeviceLocationSource(rate: LocationRate.walking);
final navigation = DeviceNavigationEngine<String>(
  route: (itineraryId, signal) async {
    final read = await mountaya.studio.itineraries.getItinerary(
      itinerary_id: itineraryId,
      options: RequestOptions(signal: signal),
    );
    return readItineraryRoute(read.data.segments, waypoints: read.data.waypoints) ??
        (throw StateError('The itinerary holds no line to follow.'));
  },
  location: location,
);
navigation.start('0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21');

// The app that made each closes it, the engine first.
navigation.close();
location.close();
await mountaya.close();
```

The plugin never asks for location access. Ask in your own flow, and declare it in `ios/Runner/Info.plist`:

```xml
<key>NSLocationWhenInUseUsageDescription</key>
<string>Your position along the route you follow.</string>
```

And in `android/app/src/main/AndroidManifest.xml`:

```xml
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
```

- `DeviceLocationSource({LocationRate rate = LocationRate.navigation, bool backgroundUpdates = false, onError})` reads positions only while the app holds location access at full accuracy: a traveller who allowed only an approximate location is read nowhere rather than kilometers away. It reads the permission again as the app resumes, and on `recheckPermission()`, which you call from the result of your own request. `standing` and `subscribe()` tell the `LocationStanding` (`authorization`, `accuracy`).
- `LocationRate.navigation` (the default) reads every fix a navigation reads: once a second on Android, iOS's best accuracy for navigation. `LocationRate.walking` reads fewer and spends less battery: on iOS `kCLLocationAccuracyBest` once the device moved 5 m, on Android every 2 seconds once it moved 5 m. A maneuver is said 55 m before it (its 50 m trigger and 5 m of slack), on time at a walker's pace up to 9 km/h.
- Each failure goes to `onError` alone as a `LocationException` whose `kind` (`LocationExceptionKind`) is `noProvider`, `providerDisabled`, `permissionRevoked`, `platformFailed` (with `detail`), `backgroundUndeclared` or `audioUndeclared`; the reader reads on. With no `onError`, failures are dropped, a debug build writing each to the console once.
- Background reading is an opt-in: `backgroundUpdates: true` keeps reading with the screen off only where the app declares `location` under `UIBackgroundModes`, and on Android `ACCESS_BACKGROUND_LOCATION` or a foreground service of type `location` it runs itself. Where it declares neither, the request is refused with `backgroundUndeclared` and positions go on while the app is in use. On iOS a voice is heard with the screen off only beside an `audio` background mode, else `audioUndeclared`. The plugin starts no foreground service and ships no navigation screen.
- `LocationSource.fromStream(positions, onError:)` takes the positions of a location stack your app already runs (`onError` is told each position the engine refuses and each error on your stream). `InertLocationSource`, the default, states nothing: hand each position to `setPosition`.
- A location source hands its positions to a function (`start(deliver)`) rather than being a `Stream`, because the engine throws a position it refuses back into the source.

## Speak the prompts

`SpeechNavigationVoice` says your sentence for each instruction. An instruction is a key and its arguments, never a sentence:

```dart
import 'package:mountaya_geo/mountaya_geo.dart';
import 'package:mountaya_navigation_flutter/mountaya_navigation_flutter.dart';

final voice = SpeechNavigationVoice(
  language: 'fr-FR',
  // Your words for each instruction. One you answer null for is not said.
  words: (instruction) => switch (instruction.key) {
    NavigationInstructionKey.turnLeft => 'Tournez à gauche sur ${instruction.name}',
    NavigationInstructionKey.turnLeftPlain => 'Tournez à gauche',
    NavigationInstructionKey.waypoint => 'Passez par ${instruction.name}',
    NavigationInstructionKey.goal ||
    NavigationInstructionKey.goalPlain => 'Vous êtes arrivé',
    _ => null,
  },
);
await voice.prepare();
await voice.close();
```

Hand it to `DeviceNavigationEngine(voice: voice)`. The engine says each maneuver once, 50 m before it.

- `SpeechNavigationVoice({required words, required String language, String? fallbackLanguage, onError})` speaks through `AVSpeechSynthesizer` on iOS and `TextToSpeech` on Android, in `language`, else `fallbackLanguage`, else the platform's own voice, lowering other apps' audio while it speaks. `prepare()` starts the engine; `close()` shuts it down. `InertNavigationVoice`, the default, says nothing.
- Failures go to `onError` as a `SpeechException` whose `kind` is `engineUnavailable` (once, where Android's speech engine did not start, so nothing is said) or `audioRefused` (per sentence whose audio the platform refused, said all the same).
- `NavigationInstructionKey` is a Dart `enum` (with `continue_` for the reserved word): a `switch` naming every key with no wildcard is told by the analyzer of each key a later contract adds. Each key has a `…Plain` twin for a step with no name. `instruction.name` and `instruction.exit` are the arguments.
- Each maneuver is announced from the step that leads to it, 50 m before that step's end (`promptMeters`) or as a shorter step begins, once per route, only while the traveller is on it. Two maneuvers on one vertex are both said, the second at the vertex; of three or more, the first and the last. The plan is Geo's (`guidancePlanOf`, `duePrompt`), so an engine of your own can say by it.

## Show progress

The engine's state carries the progress. Read it in a widget through a `NavigationListenable`:

```dart
import 'package:flutter/widgets.dart';
import 'package:mountaya_geo/mountaya_geo.dart';
import 'package:mountaya_navigation_flutter/mountaya_navigation_flutter.dart';

class NavigationBanner extends StatefulWidget {
  const NavigationBanner({super.key, required this.navigation});

  final NavigationEngine<String> navigation;

  @override
  State<NavigationBanner> createState() => _NavigationBannerState();
}

class _NavigationBannerState extends State<NavigationBanner> {
  static const _units = UnitPreferences(language: 'en');

  // Made once, never inside build, and disposed with the State.
  late final NavigationListenable _state = NavigationListenable(widget.navigation);

  @override
  void dispose() {
    _state.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) => ValueListenableBuilder<NavigationState>(
    valueListenable: _state,
    builder: (context, navigation, _) => switch (navigation.progress) {
      final progress? => Text(
        '${formatDistance(progress.toManeuver.distance, _units)} to the next turn, '
        '${formatDistance(progress.toArrival.distance, _units)} to go',
      ),
      null => Text(navigation.status.id),
    },
  );
}
```

- `NavigationState`: `status`, `route` (the `FollowedRoute`), `progress` and `error`. `NavigationProgress`: `along` (meters along the route), `step`, `next`, `toManeuver` and `toArrival`, each a `NavigationRemainder` with `distance` (meters) and `duration` (seconds, `null` where the route states none).
- `NavigationListenable(engine)` is a `ValueListenable<NavigationState>` for a `ValueListenableBuilder`, disposed by whoever made it; `engine.asValueListenable()` (the `NavigationEngineValueListenable` extension) answers one too. Make either once, where you make the engine, never inside `build`, where a new one each frame listens again. `subscribe()` is a broadcast stream that hands a late listener nothing: a reader takes `state` first.
- `positionAtMetersRoute(route, meters)` places a marker at a distance along the followed route; draw the route itself on a map with `mountaya_elements_flutter`.

## Replay a route

`ReplayLocationSource` walks each route the engine follows at the speed you name, for a demo or a test:

```dart
import 'package:mountaya_client/mountaya_client.dart';
import 'package:mountaya_geo/mountaya_geo.dart';
import 'package:mountaya_navigation_flutter/mountaya_navigation_flutter.dart';

const publishableKey = String.fromEnvironment('MOUNTAYA_PUBLISHABLE_KEY');

final mountaya = Mountaya(credential: .publishable(key: publishableKey));
final replay = ReplayLocationSource(metersPerSecond: 10);
final navigation = DeviceNavigationEngine<String>(
  route: (itineraryId, signal) async {
    final read = await mountaya.studio.itineraries.getItinerary(
      itinerary_id: itineraryId,
      options: RequestOptions(signal: signal),
    );
    return readItineraryRoute(read.data.segments, waypoints: read.data.waypoints) ??
        (throw StateError('The itinerary holds no line to follow.'));
  },
  location: replay,
);
navigation.start('0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21');
await navigation.subscribe().firstWhere(
  (state) => state.status == NavigationStatus.arrived,
);
navigation.close();
await mountaya.close();
```

- `ReplayLocationSource({required double metersPerSecond, Duration interval = const Duration(seconds: 1)})` (it has no `close()`: the engine starts and stops it) walks each route followed from its start, stated the moment the route lands, on Dart's timers and the device's monotonic clock, so a test under `fake_async` drives it.
- Trail's Replay switch swaps this source in for `DeviceLocationSource`, at 10 m/s, with no location access asked.
- A `ScriptedNavigationEngine` in tests answers each route request yourself: see [testing](https://docs.mountaya.com/en/sdks/dart/testing.md#navigation).

## Next steps

- [Testing](https://docs.mountaya.com/en/sdks/dart/testing.md): Script the navigation in your tests.
- [Show a map](https://docs.mountaya.com/en/sdks/dart/map.md): Draw the route and the traveller on a map.
