# Turn-by-turn navigation

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

Follow a Mountaya itinerary turn by turn in Swift: read its route, follow the device's position, speak each maneuver and show progress.

`MountayaNavigation` follows a route on the device: it reads your position, says each maneuver in your words, and tells you what is left until you arrive.

## Read the route

A saved itinerary is followed whole, as one route with its steps:

```swift
import MountayaClient
import MountayaGeo

struct NoRoute: Error {}

// Reads the Tour du Mont-Blanc into the route an engine follows, or throws where it has none.
func readRoute(through mountaya: Mountaya) async throws -> NavigationRoute {
  let itinerary = try await mountaya.studio.itineraries.getItinerary(
    itinerary_id: "0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21")
  guard let route = readItineraryRoute(itinerary.data.segments, waypoints: itinerary.data.waypoints)
  else { throw NoRoute() }
  return route
}
```

- `readItineraryRoute(_:waypoints:)` joins the itinerary's segments in their chain order, each followed by its own steps, and says every arrival but the last as a `.waypoint`, named by the itinerary's waypoint standing where its segment ends. It answers nil for an itinerary with no line.
- A Data API route reads the same way: `readDirectionsSteps(_:coordinateCount:)` over a `directions` route's steps, then `NavigationRoute(line:steps:duration:)`. `followedRouteOf(_:)` follows a route with no steps.
- Positions are `[longitude, latitude]`.

## Follow the route

An engine takes a route source and the positions you hand it. `RouteFollowingEngine` is the engine with no device behind it:

```swift
import MountayaClient
import MountayaGeo

struct NoRoute: Error {}

@MainActor
func follow(through mountaya: Mountaya) async throws {
  let navigation = RouteFollowingEngine<String>(route: { id in
    let itinerary = try await mountaya.studio.itineraries.getItinerary(itinerary_id: id)
    guard
      let route = readItineraryRoute(itinerary.data.segments, waypoints: itinerary.data.waypoints)
    else { throw NoRoute() }
    return route
  })
  navigation.start("0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21")

  // Hand positions once the route has loaded: here, the start in Chamonix.
  for await state in navigation.subscribe() where state.status == .navigating {
    try navigation.setPosition([6.8712, 45.9231])
    print(navigation.state.progress?.toArrival.distance ?? 0, "meters to go")
    break
  }
}
```

`state` is observable, so a SwiftUI view that reads it is drawn again as you move.

- Every engine conforms to `NavigationEngine` (`start(_:)`, `stop()`, `reroute(_:)`, `setPosition(_:)`, `state`, `subscribe()`, `close()`) and is bound to the main actor. `start` asks the route source for a route; `reroute(_:)` alone asks for a new one.
- `NavigationStatus`: `.idle`, `.routing`, `.navigating`, `.offRoute` (more than 50 m from the route), `.rerouting`, `.arrived`, `.failed`. `state.error` is a `NavigationError` (with `kind` and `cause`) for why the last route request failed.
- `setPosition(_:)` throws `PositionError` for a position that names no place.
- `RouteFollowingEngine(route:onChange:)` is the contract's machine, in `MountayaGeo`, for an app that links Geo alone. `DeviceNavigationEngine` is the same machine with a location source and a voice.
- The words are yours: `stepInstruction(_:)` answers a `NavigationInstruction` (`key`, `name`, `exit`), a copy key and its arguments, never a sentence.

## Use the device's location

`DeviceNavigationEngine` reads the device's position while your app holds the permission. Your app asks for it, and says why in Info.plist:

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

```swift
import CoreLocation
import MountayaClient
import MountayaGeo
import MountayaNavigation

struct NoRoute: Error {}

@MainActor
func navigate(through mountaya: Mountaya, access: CLLocationManager) -> DeviceNavigationEngine<String>
{
  access.requestWhenInUseAuthorization()
  let navigation = DeviceNavigationEngine<String>(
    route: { id in
      let itinerary = try await mountaya.studio.itineraries.getItinerary(itinerary_id: id)
      guard
        let route = readItineraryRoute(itinerary.data.segments, waypoints: itinerary.data.waypoints)
      else { throw NoRoute() }
      return route
    },
    location: DeviceLocationSource(rate: .walking))
  navigation.start("0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21")
  return navigation
}
```

- `DeviceLocationSource(rate:backgroundUpdates:onError:)` never asks for permission. `standing` (a `LocationStanding`: `authorization` `.notDetermined`, `.denied`, `.restricted`, `.whenInUse`, `.always`; `accuracy` `.full` or `.reduced`) is observable; `recheckPermission()` reads it again after your own request.
- `rate: .navigation` (default) reads every fix; `.walking` reads a fix once the device moved 5 m, which still says each prompt between 55 and 50 m before its maneuver.
- Background navigation: declare `location` under `UIBackgroundModes` (with `audio` for the voice to speak with the screen off) and make the source with `backgroundUpdates: true`. Without `location` the source tells `onError` a `LocationError` of kind `.backgroundUndeclared` and reads while the app is in use; without `audio`, `.audioUndeclared`, and the voice is silent with the screen off.
- `LocationError.Kind` is an open set: `.providerDisabled`, `.permissionRevoked`, `.platformFailed` (carried as `cause`), `.backgroundUndeclared`, `.audioUndeclared`, `.noProvider` (Android only). A source given no `onError` drops every failure; a debug build prints it.
- Other sources: `StreamLocationSource(_:onError:)` states the positions an `AsyncSequence` of yours yields; `InertLocationSource`, the default, states nothing and you call `setPosition(_:)`. `LocationSource` is the protocol for your own.
- The engine closes neither its source nor its voice: the app that made one ends it. The engine builds on every platform; on platforms without Core Location, hand positions yourself.

## Speak the prompts

`SpeechNavigationVoice` says your sentence for each instruction, in the language you name:

```swift
import MountayaGeo
import MountayaNavigation

@MainActor
func frenchVoice() -> SpeechNavigationVoice {
  // Your words for each instruction. One you answer nil for is not said.
  SpeechNavigationVoice(language: "fr-FR") { instruction in
    switch instruction.key {
    case .turnLeft: "Tournez à gauche sur \(instruction.name ?? "")"
    case .turnLeftPlain: "Tournez à gauche"
    case .waypoint: "Passez par \(instruction.name ?? "")"
    case .goal, .goalPlain: "Vous êtes arrivé"
    default: nil
    }
  }
}
```

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

- `SpeechNavigationVoice(language:fallbackLanguage:onError:words:)` exists on iOS, iPadOS and Mac Catalyst. It lowers other apps' audio while it speaks, and uses `fallbackLanguage` where the device has no voice for `language`. `prepare()` looks the voice up ahead of the first sentence, `hush()` stops it, `close()` ends it.
- `onError` hears each time the system refuses the audio session: a `SpeechError` of kind `.audioRefused`, the sentence said all the same. `.engineUnavailable` is the other kind.
- 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. At `DeviceLocationSource(rate: .walking)` the prompt falls between 55 and 50 m before the maneuver. Each key has a `…Plain` twin for a step with no name; `instruction.name` and `instruction.exit` are the arguments.
- `words` answers nil to say nothing for an instruction. `InertNavigationVoice`, the default, says nothing. `NavigationVoice` is the protocol for your own (`say(_:)`, `hush()`).
- `readItineraryRoute` says a place passed on the way with the keys `waypoint` (with its name) and `waypointPlain`, and the arrival with `goal` or `goalPlain`, once, at the end.
- When each maneuver is announced is Geo's: `guidancePlanOf(_:)` and `duePrompt(_:progress:)`, for an engine of your own that speaks at the same meter.

## Show progress

`state.progress` says how far it is to the next maneuver and to the arrival:

```swift
import MountayaGeo
import MountayaNavigation
import SwiftUI

struct Progress: View {
  let navigation: DeviceNavigationEngine<String>
  let units = UnitPreferences(language: "en")

  var body: some View {
    if let progress = navigation.state.progress {
      Text("\(formatDistance(progress.toManeuver.distance, units: units)) to the next turn")
      Text("\(formatDistance(progress.toArrival.distance, units: units)) to go")
    }
  }
}
```

- `NavigationProgress`: `step` (the step being followed), `next`, `along` (meters along the route), `toManeuver` and `toArrival`, each a `NavigationRemainder` with `distance` (meters) and `duration` (seconds, where the route states one).
- `navigationProgressAt(_:position:previous:)` is the rule behind it, for an engine of your own.
- `subscribe()` hands any other reader every state in order, as an `AsyncStream<NavigationState>`.

## Replay a route

`ReplayLocationSource` walks the route at a speed you name, for a demo or a test on the simulator:

```swift
import MountayaGeo
import MountayaNavigation

@MainActor
func demo(_ route: NavigationRoute) -> DeviceNavigationEngine<NavigationRoute> {
  let navigation = DeviceNavigationEngine<NavigationRoute>(
    route: { $0 }, location: ReplayLocationSource(metersPerSecond: 10))
  navigation.start(route)
  return navigation
}
```

- `ReplayLocationSource(metersPerSecond:interval:clock:)` walks each route followed, a tick every `interval` (1 second by default), read off the measure the route was followed with (`positionAtMeters(_:meters:)` over the `FollowedRoute`), on a clock that stands still while the device sleeps.
- A test drives an engine with no device through `ScriptedNavigationEngine` ([testing](https://docs.mountaya.com/en/sdks/swift/testing.md#navigation)).
- The sample app Trail replays at 10 m/s; its UI test walks the whole journey at 100 m/s.

## Next steps

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