# Turn-by-turn navigation

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

Follow an itinerary with RouteFollowingEngine on every target, or navigate on an Android device with DeviceNavigationEngine, spoken prompts and replay.

A navigation follows a route you hand it, from positions you or the device give it. `RouteFollowingEngine` runs on every target. On Android, `DeviceNavigationEngine` adds the device's location and its voice.

## Read the route

`readItineraryRoute` joins a saved itinerary's segments into one route to follow:

```kotlin
import com.mountaya.client.Mountaya
import com.mountaya.geo.NavigationRoute
import com.mountaya.geo.readItineraryRoute

suspend fun tourRoute(mountaya: Mountaya, itineraryId: String): NavigationRoute {
    val itinerary = mountaya.studio.itineraries.getItinerary(itineraryId).data
    return readItineraryRoute(itinerary.segments, itinerary.waypoints) ?: error("$itineraryId has no route to follow.")
}
```

- `readItineraryRoute(segments, waypoints)` joins the segments in chain order into one `NavigationRoute` (`line`, `steps`, `duration`), each arrival but the last said as a waypoint passed, by the name of the itinerary's waypoint standing within 60 m of where its segment ends. It answers null where no segment holds a line. The duration is the segments' durations summed, none where a segment holding a line states none.
- A Data API route reads the same way: `readDirectionsSteps(route.steps, coordinateCount = line.coordinates.size)` answers the steps of a `directions` route, and `NavigationRoute(line.coordinates, steps.steps, route.duration)` the route.
- A route source is a `NavigationRouteSource<T>`, `suspend (T) -> NavigationRoute`, called on `start(request)` and on `reroute(request)` alone. It is yours, so it reads through your own client.

## Follow the route

`RouteFollowingEngine` is the navigation on every target: hand it positions, and read its state:

```kotlin
import com.mountaya.client.Mountaya
import com.mountaya.geo.RouteFollowingEngine
import com.mountaya.geo.readItineraryRoute
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.first

suspend fun follow(scope: CoroutineScope, mountaya: Mountaya): RouteFollowingEngine<String> {
    val navigation =
        RouteFollowingEngine<String>(scope) { itineraryId ->
            val itinerary = mountaya.studio.itineraries.getItinerary(itineraryId).data
            readItineraryRoute(itinerary.segments, itinerary.waypoints) ?: error("No route to follow.")
        }
    navigation.start("0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21")
    // Wait for the route, then hand each position your app reads, [longitude, latitude].
    navigation.state.first { it.route != null }
    navigation.setPosition(listOf(6.8712, 45.9231))
    return navigation
}
```

- `RouteFollowingEngine<T>(scope, route, onChange = null)` lives in `mountaya-geo` and runs on the jvm, Android and iOS. It is a `NavigationEngine<T>`: `start(request)`, `setPosition(position)`, `reroute(request)`, `stop()`, `close()` (an `AutoCloseable`), and `state`, a `StateFlow<NavigationState>`. `onChange` is told each state inline, before the `StateFlow` holds it.
- `NavigationState`: `status` (`NavigationStatus.Idle`, `Routing`, `Navigating`, `OffRoute`, `Rerouting`, `Arrived`, `Failed`), `route` (the `FollowedRoute`), `progress` and `error`. A traveller more than 50 m from the route is `OffRoute`; a new route is asked for by `reroute` alone, never by the engine.
- Run it on the scope whose dispatcher you drive it from (`viewModelScope`, `lifecycleScope`).
- It answers what `DeviceNavigationEngine` and `ScriptedNavigationEngine` answer for the same positions: the same status, progress and arrival, at the same meter as the other SDKs.
- The guidance rules are Geo's too: `guidancePlanOf(followedRoute)` and `duePrompt(plan, progress)` say which maneuver falls due where, for an engine of your own that speaks.

## Use the device's location

On Android, `DeviceNavigationEngine` reads the device's satellite position while your app holds `ACCESS_FINE_LOCATION`:

```kotlin
import android.content.Context
import com.mountaya.client.Mountaya
import com.mountaya.geo.readItineraryRoute
import com.mountaya.navigation.DeviceLocationSource
import com.mountaya.navigation.DeviceNavigationEngine
import com.mountaya.navigation.LocationRate
import kotlinx.coroutines.CoroutineScope

fun guided(scope: CoroutineScope, context: Context, mountaya: Mountaya): DeviceNavigationEngine<String> =
    DeviceNavigationEngine(
        scope = scope,
        route = { itineraryId ->
            val itinerary = mountaya.studio.itineraries.getItinerary(itineraryId).data
            readItineraryRoute(itinerary.segments, itinerary.waypoints) ?: error("No route to follow.")
        },
        // A walker's rate: a fix every two seconds once the device moved 5 m.
        location = DeviceLocationSource(context, rate = LocationRate.Walking),
    )
```

Ask for location access in your app's own flow first. The engine never asks.

- `mountaya-navigation` is Android only. `DeviceNavigationEngine(scope, route, location = InertLocationSource(), voice = InertNavigationVoice())` drives Geo's `RouteFollowingEngine` and Geo's guidance rules directly, and links no navigation library.
- `DeviceLocationSource(context, rate = LocationRate.Navigation, backgroundUpdates = false, onError = null)`: `LocationRate.Navigation` is every fix the platform reads, a fix a second; `LocationRate.Walking` a fix every two seconds once the device moved 5 m, still on time for a prompt at a walker's pace.
- It reads under `ACCESS_FINE_LOCATION` alone: under the approximate permission it reads nothing, `standing` stating `LocationAccuracy.Reduced`. `standing` (a `StateFlow<LocationStanding?>`, `authorization` and `accuracy`) is read again each time the app returns to the foreground; call `recheckPermission()` from your own permission request's result.
- `onError` hears each failure as a `LocationException` whose `kind` is `NoProvider`, `PermissionRevoked`, `ProviderDisabled`, `PlatformFailed` (the platform's failure as `cause`) or `BackgroundUndeclared`. A source given no `onError` drops each failure and logs it once with `Log.w` where the app is debuggable.
- `backgroundUpdates = true` keeps reading with the screen off where the merged manifest declares `ACCESS_BACKGROUND_LOCATION` or a foreground service of type `location` the app runs; where it declares neither, the source tells `BackgroundUndeclared` as it starts and reads while the app is in use.
- `FlowLocationSource(scope, flow, onError)` states the positions of your own `Flow`; `InertLocationSource()` states nothing and you call `setPosition`. A `LocationSource` of your own implements `start(deliver)`, `stop()` and `follow(route)`.

## Speak the prompts

`SpeechNavigationVoice` says each maneuver through the platform's text-to-speech, in your words:

```kotlin
import android.content.Context
import com.mountaya.geo.NavigationInstruction
import com.mountaya.geo.NavigationInstructionKey
import com.mountaya.navigation.SpeechNavigationVoice
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch

fun frenchVoice(scope: CoroutineScope, context: Context): SpeechNavigationVoice {
    val voice = SpeechNavigationVoice(context, "fr-FR") { instruction -> sentence(instruction) }
    // Learn before the first maneuver whether the speech engine starts.
    scope.launch { voice.prepare() }
    return voice
}

// Your words for each instruction. One you answer null for is not said.
fun sentence(instruction: NavigationInstruction): String? =
    when (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é"
        else -> null
    }
```

Hand it to the engine as `voice = frenchVoice(scope, context)`. The engine says each maneuver once, 50 m before it.

- `SpeechNavigationVoice(context, language, fallbackLanguage = null, onError = null, sentence)` speaks your sentence for each instruction in `language`, or in `fallbackLanguage` where the device holds no voice for the first, as navigation guidance, taking the audio focus while it speaks. A sentence answered `null` is not said. Close it with `close()`.
- An instruction is a copy key (`NavigationInstructionKey`) and its arguments (`name`, `exit`). `readItineraryRoute` adds two keys no directions answer writes: `Waypoint` and `WaypointPlain`. Each maneuver is said once, `PROMPT_METERS` (50 m) before the end of the step that leads to it, or as the step begins where the step is shorter (`guidancePlanOf`, `duePrompt`), and only while the traveller is on the route.
- `onError` hears a `SpeechException` whose `kind` is `EngineUnavailable` (the speech engine fails to start, once, which `prepare()` waits for) or `AudioRefused` (the platform refused the audio focus; the sentence is said anyway). The kinds are the ones the Swift and Dart SDKs name.
- The manifest needs nothing: `mountaya-navigation` merges the `TTS_SERVICE` query Android 11 and later need. `InertNavigationVoice()`, the default, says nothing; a `NavigationVoice` of your own implements `say(instruction)` and `hush()`.

## Show progress

The state holds what is left to the next maneuver and to the arrival:

```kotlin
import com.mountaya.geo.NavigationEngine
import com.mountaya.geo.NavigationStatus
import com.mountaya.geo.UnitPreferences
import com.mountaya.geo.formatDistance
import com.mountaya.geo.formatDuration

suspend fun showProgress(navigation: NavigationEngine<String>) {
    val units = UnitPreferences("en")
    navigation.state.collect { state ->
        val progress = state.progress
        when {
            state.status == NavigationStatus.Arrived -> println("Arrived")
            progress != null -> println("${formatDistance(progress.toManeuver.distance, units)} to the next turn, ${formatDuration(progress.toArrival.duration, units)} left")
            else -> println(state.status)
        }
    }
}
```

- `NavigationProgress`: `along` (meters from the route's first vertex), `step` (the index of the step the traveller is in), `next` (the step after it, whose maneuver is next, or null after the last), `toManeuver` and `toArrival`, each a `NavigationRemainder` (`distance` in meters along the line, `duration` in seconds, null where a step states none).
- `navigationProgressAt(followedRoute, position, along)` answers the same progress for a position, with no engine.
- In Compose, collect it with `collectAsState()`.

## Replay a route

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

```kotlin
import com.mountaya.geo.NavigationRoute
import com.mountaya.navigation.DeviceNavigationEngine
import com.mountaya.navigation.ReplayLocationSource
import kotlinx.coroutines.CoroutineScope
import kotlin.time.Duration.Companion.seconds

fun replay(scope: CoroutineScope, route: NavigationRoute): DeviceNavigationEngine<Unit> {
    val navigation =
        DeviceNavigationEngine<Unit>(
            scope = scope,
            route = { route },
            location = ReplayLocationSource(scope, metersPerSecond = 10.0, interval = 1.seconds),
        )
    navigation.start(Unit)
    return navigation
}
```

- `ReplayLocationSource(scope, metersPerSecond, interval, timeSource = TimeSource.Monotonic)` states the route's start at once, then, every `interval`, the position `metersPerSecond` times the time elapsed on `timeSource` along the line, read off the route's own measure (`positionAtMeters(route, meters)`), ending on its last position. A new route is walked from its start.
- Under `runTest`, hand it `testScheduler.timeSource`: a walk of an hour takes none.
- On the jvm or iOS, replay with `RouteFollowingEngine` and your own loop over `positionAtMeters`, or test with `ScriptedNavigationEngine` (see [testing](https://docs.mountaya.com/en/sdks/kotlin/testing.md#navigation)).

## Next steps

- [Testing](https://docs.mountaya.com/en/sdks/kotlin/testing.md): Script the API, the map and the navigation.
- [Geo without a map](https://docs.mountaya.com/en/sdks/kotlin/geo.md): The rules every engine stands on.
