Get started
TypeScript SDK
Geo and navigation

Turn-by-turn navigation

Turn-by-turn navigation

@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:

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.

Follow the route

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

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.

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:

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.

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:

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))));
  });
};

Show progress

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

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`,
    );
  });

Replay a route

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

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.

Next steps

Last updated