# Turn-by-turn navigation

> Canonical URL: https://docs.mountaya.com/en/sdks/typescript/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: read its route, feed the device's position, speak each maneuver and show what is left.

`@mountaya/elements/navigation` tells a traveller what to do next, how far is left, and when they leave the route. It draws nothing and makes no request of its own. The position and the voice come from your app.

## Read the route

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

```ts
import { readItineraryRoute } from "@mountaya/elements/navigation";

const { data: itinerary } = await mountaya.studio.itineraries.getItinerary({
  itinerary_id: "0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21",
});

const route = readItineraryRoute(itinerary.segments, itinerary.waypoints);
if (route === null) throw new Error("This itinerary has no line to follow.");

console.log(route.steps.length, route.duration); // the steps, and the seconds the route takes
```

Each step says what to do where it starts: turn left, keep right, reach a waypoint.

- `readItineraryRoute(segments, waypoints)` answers a `NavigationRoute` (`duration` in seconds or `null`, `line`, the positions as GeoJSON writes them, and `steps`) or `null` where no segment holds a line. Segments are laid end to end in `position` order; each is followed by its own steps where they tile its line, and otherwise as a departure over the line and an arrival on its last vertex. The arrival between two segments is said as the waypoint standing there (within 60 m of the joint), since the traveller arrives only where the route ends.
- A `NavigationStep` is `{ maneuver, name, distance, duration, exitNumber, fromIndex, toIndex }`, `fromIndex` and `toIndex` indexing `line`. `maneuver` is a `ManeuverType`: `turn-left`, `turn-right`, `sharp-left`, `sharp-right`, `slight-left`, `slight-right`, `continue`, `enter-roundabout`, `exit-roundabout`, `uturn`, `goal`, `depart`, `keep-left`, `keep-right`, `unknown`, or `waypoint`.
- For a route the Data API answers instead, `readDirectionsSteps(route.steps, line.length)` reads its steps; `readItineraryDirectionsSteps` reads a REST directions segment's. A maneuver this release does not know reads as `unknown` rather than dropping the step, and a step list whose vertex ranges do not cover the line once, in order, is refused whole: the route is then followed as one with no steps.
- A session token naming a member reads the itinerary's draft; a key alone reads what was last published.

## Follow the route

`NavigationEngine` asks your route source for a route, then follows it:

```ts
import { NavigationEngine, readItineraryRoute } from "@mountaya/elements/navigation";

const navigation = new NavigationEngine({
  route: async (itineraryId: string, { signal }) => {
    const { data } = await mountaya.studio.itineraries.getItinerary(
      { itinerary_id: itineraryId },
      { signal },
    );
    const route = readItineraryRoute(data.segments, data.waypoints);
    if (route === null) throw new Error("This itinerary has no line to follow.");
    return route;
  },
});

navigation.subscribe(() => console.log(navigation.getSnapshot().status));
navigation.start("0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21"); // routing, then navigating
```

Call `stop()` when the traveller stops, and `dispose()` when the screen goes away.

- `new NavigationEngine({ route })` takes a route source, `(request, { signal }) => Promise<NavigationRoute>`. `request` is whatever your app asks a route for (an itinerary id, waypoints, a destination), handed to it as `start(request)` or `reroute(request)` passed it. The signal aborts when the navigation stops or a newer request replaces the one in flight.
- `getSnapshot()` answers `{ status, route, progress, error }`, replaced on every change; `subscribe(listener)` returns its unsubscribe. The pair is `useSyncExternalStore`'s two arguments, so React, Vue or Svelte bind it directly.
- Statuses (`NAVIGATION_STATUSES`): `idle`, `routing`, `navigating`, `off-route`, `rerouting`, `arrived`, `failed`. A position more than 50 m from the route is `off-route`, the same distance in every SDK, and back within it is `navigating`; a traveller whose progress reaches the end has `arrived`. A first route that fails leaves the navigation `failed`, with the reason in `error`, always an `Error`.
- `reroute(request)` asks for a new route from where the traveller is, only while `off-route`; the route held stays followed until the new one lands, and stays where it fails (`off-route`, with `error`). At most one request is in flight: a start or a reroute made meanwhile waits, and only the newest waits.
- `stop()` returns to `idle`, drops the route and abandons any request. `dispose()` also drops every listener; a command after it does nothing.
- `followedRouteOf(route)` answers the steps a route is followed by, a departure and an arrival for a route with none, for a machine of your own.

## Use the device's location

The SDK reads no location. Once the route is held, feed it the positions your app gets, here from the browser:

```ts
import type { NavigationEngine } from "@mountaya/elements/navigation";

/** follow feeds the device's position to a navigation once its route lands, until stopped. */
export const follow = (navigation: NavigationEngine<string>): (() => void) => {
  let watch: number | null = null;
  const startWhenRouted = () => {
    if (watch !== null || navigation.getSnapshot().route === null) return;
    watch = navigator.geolocation.watchPosition(
      ({ coords }) => navigation.setPosition([coords.longitude, coords.latitude]),
      (error) => console.warn(error.message),
      { enableHighAccuracy: true },
    );
  };
  const unsubscribe = navigation.subscribe(startWhenRouted);
  startWhenRouted();

  return () => {
    unsubscribe();
    if (watch !== null) navigator.geolocation.clearWatch(watch);
  };
};
```

In a native shell such as Capacitor or React Native, pass the positions its location plugin reports.

- `setPosition([longitude, latitude])` reads a position against the route: the progress, off-route, the arrival. With no route held yet it is kept and read against the route that lands next. A coordinate that is not a finite number throws `MountayaElementsError`.
- The engine never asks for permission, never filters accuracy and never smooths a position: those are the app's. The browser's `watchPosition` asks the reader first, and works only on a secure origin. The TypeScript SDK ships no location source for navigation.
- On a map, `map.locate()` and `GeolocateControl` read the map's own `geolocation` (`browserGeolocation()` of `@mountaya/elements/seams` by default), which a host may replace with its own source.

## Speak the prompts

The SDK speaks nothing either. `stepInstruction` answers a key and its arguments, never a sentence, so the words are yours in every language:

```ts
import {
  type NavigationEngine,
  type NavigationInstruction,
  stepInstruction,
} from "@mountaya/elements/navigation";

const phrase = (instruction: NavigationInstruction): string => {
  switch (instruction.key) {
    case "turn-left":
      return `Turn left onto ${instruction.arguments.name}`;
    case "turn-leftPlain":
      return "Turn left";
    case "roundaboutExit":
      return `At the roundabout, take exit ${instruction.arguments.exit}`;
    default:
      return "Continue";
  }
};

/** announce says each maneuver once, 50 meters before it. */
export const announce = (navigation: NavigationEngine<string>): (() => void) => {
  let said = -1;
  return navigation.subscribe(() => {
    const { progress, route, status } = navigation.getSnapshot();
    const next = progress?.next ?? null;
    if (status !== "navigating" || progress === null || next === null || next === said) return;
    const step = route?.steps[next];
    if (step === undefined || progress.toManeuver.distance > 50) return;
    said = next;
    speechSynthesis.speak(new SpeechSynthesisUtterance(phrase(stepInstruction(step))));
  });
};
```

- `stepInstruction(step)` answers `{ key, arguments }`. Each maneuver has two keys: its own (`turn-left`), which takes the way's `name`, and its `Plain` twin (`turn-leftPlain`), which takes nothing and is said where no way is named (no name, an empty one, or `-`). A roundabout entered or left with an exit greater than 0 is said with `roundaboutExit` (`exit`, `name`) or `roundaboutExitPlain` (`exit`). `waypoint` and `waypointPlain` say an arrival at a waypoint by its name. A maneuver outside the vocabulary is said as `unknown`.
- `NAVIGATION_INSTRUCTION_KEYS` is every key there is: a test of your own strings can hold a sentence for each.
- The contract's prompt rule (`geo.navigation.prompts`), which an engine that speaks follows: each maneuver is announced 50 m before the end of the step it ends (as the step begins where the step is shorter), once per route, and only while `navigating`. The TypeScript SDK publishes no prompt rule and no voice; an app that follows the rule announces each maneuver at the same meter as any Mountaya SDK that speaks.

## Show progress

The snapshot's `progress` says how far and how long to the next maneuver and to the arrival:

```ts
import type { NavigationEngine } from "@mountaya/elements/navigation";
import { formatDuration, formatNavDistance } from "@mountaya/elements/profile";

export const showProgress = (navigation: NavigationEngine<string>): (() => void) =>
  navigation.subscribe(() => {
    const { progress } = navigation.getSnapshot();
    if (progress === null) return;
    const units = { language: "en", length: "metric" } as const;
    console.log(
      `In ${formatNavDistance(progress.toManeuver.distance, units)},`,
      `${formatDuration(progress.toArrival.duration, units)} to go`,
    );
  });
```

- `NavigationProgress` is `{ along, step, next, toManeuver, toArrival }`: `along` meters from the first vertex, `step` the index of the current step, `next` the index of the step whose maneuver comes next (`null` after the last), and each remainder `{ distance, duration }`, in meters and seconds. `duration` is `null` where a step states none.
- Distances are measured along the route's own geometry, a vertex that names no place measured across, and times are the steps' own durations, prorated within the current step.
- `navigationProgressAt(route, position, previous)` is the rule under the engine, for a machine of your own: `previous` is the progress the last position read, in meters (0 on a fresh route).
- `formatNavDistance` and `formatDuration` (`@mountaya/elements/profile`) write the figures in the reader's language and units. On a map, draw the followed `line` with `map.setPreview` or a layer of your own, and the traveller with `map.addMarker`.

## Replay a route

To try a screen at your desk, walk the route's own line at 10 m/s instead of the device:

```ts
import { haversineMeters } from "@mountaya/elements/geo";
import type { NavigationEngine } from "@mountaya/elements/navigation";

/** replay walks the followed route at 10 meters a second, one position each second. */
export const replay = (navigation: NavigationEngine<string>): (() => void) => {
  const line = navigation.getSnapshot().route?.line;
  if (line === undefined || line.length === 0) throw new Error("Replay once the route is held.");

  let vertex = 0;
  let along = 0; // meters walked past line[vertex]
  const timer = setInterval(() => {
    along += 10;
    while (vertex < line.length - 1 && along >= haversineMeters(line[vertex], line[vertex + 1])) {
      along -= haversineMeters(line[vertex], line[vertex + 1]);
      vertex += 1;
    }
    const from = line[vertex];
    const to = line[vertex + 1] ?? from;
    const leg = haversineMeters(from, to);
    const t = leg === 0 ? 0 : along / leg;
    navigation.setPosition([from[0] + (to[0] - from[0]) * t, from[1] + (to[1] - from[1]) * t]);
    if (vertex === line.length - 1) clearInterval(timer);
  }, 1000);

  return () => clearInterval(timer);
};
```

Call it once the route is held, when the status is `navigating`. The last position reports `arrived`.

- A replay is a test of your screen, not of the engine: the engine reads each position as it would a device's. To exercise off-route and rerouting, feed a position more than 50 m from the line.
- In a unit test, call `setPosition` synchronously with the positions you want and read `getSnapshot()` after each: there is no timer inside the engine. A route source resolving a fixed `NavigationRoute` keeps the test off the network.
- The native SDKs publish a scripted navigation engine for tests; TypeScript needs none, since the engine already takes every position from its caller.

## Next steps

- [Geo without a map](https://docs.mountaya.com/en/sdks/typescript/geo.md): Distances, elevation and units.
- [Show a map](https://docs.mountaya.com/en/sdks/typescript/map.md): Draw the route under the traveller.
