Skip to content
Documentation menu
docs / core-reference · raw .md

@mapmap/core reference

Generated from the published @mapmap/core 0.4.0 type declarations by website/scripts/sdk-reference.mjs. Do not edit by hand: change the JSDoc in the package, or the examples in website/content/sdk-reference/core.examples.md, and regenerate.

Every public export of the WASM core: the guidance session, the navigation state machine, route adapters, ADR tunnel checks and polyline helpers. The package is generated from the Rust core with wasm-bindgen, so many parameters are typed any in the published declarations; the descriptions say what each one takes. The guide is Core (WASM) in SDKs & installation.

bash
npm install @mapmap/core@0.4.0

Other SDK references: @mapmap/maps, @mapmap/points, @mapmap/tile, @mapmap/react-native, @mapmap/voice, MapMapKit, ai.mapmap:core.

67 exports across 2 entry points: 6 classes, 13 functions, 24 interfaces, 24 types.

How to read this page

Each entry gives the declaration as published, the JSDoc description, and a table of parameters or properties with their types. The Default column quotes the default the source states (an @default tag or a "Default ..." sentence in the JSDoc). "required" means the property must be given; "not stated" means the source gives no default, so none is claimed here. Classes, factories and the main entry functions each carry a minimal example; examples marked from the source are the package's own @example.

Contents

  • @mapmap/core: 67 exports
  • @mapmap/core/web: the same declarations as @mapmap/core.
  • @mapmap/core/node: no exports of its own, 62 re-exported from an earlier entry point

@mapmap/core

ts
import { /* … */ } from "@mapmap/core";

Classes (@mapmap/core)

GuidanceSession, NavigationController, NavigationReplay, NavigationSession, NavigationSessionRecording, RouteAdapter

GuidanceSession

Class · also exported from @mapmap/core/node

ts
class GuidanceSession { … }

A turn-by-turn guidance session over one route, the same Ferrostar-backed state machine the mobile SDKs run, driven from JS.

Construct it from a Valhalla route response JSON, then stream location fixes in with GuidanceSession::update_location; each call returns the updated guidance state. Bound to a single route, recalculate by building a new session.

PropertyTypeDefaultDescription
readonly totalStepsnumberNumber of steps in the route, including the arrival step.

Constructor and methods

  • free(): void
  • [Symbol.dispose](): void
  • advanceToNextStep(): any: Manually advance to the next step (e.g. in a tunnel with no GNSS, or from an agent runtime that steps the route programmatically).
  • enableProbe(config: any): void: Enable opt-in aggregate probe collection for this session. Off until called; call once before streaming fixes. config is a plain object mirroring the mobile ProbeConfig plus optional routeRef, territory and vehicleClass: { enabled: true, tripEndSuppressionM, routeRef, territory, vehicleClass, … }. Consent is the caller's responsibility: only enable this for a key whose operator has set probe_opt_in, and, in a browser, only with the user's opt-in consent. See docs/PROBE-SDK-INTEGRATION.md. Only aggregates are ever produced; the collector cannot emit a trajectory.
  • finishProbeJson(arrived: boolean, timestamp_ms: number): string | undefined: Close the trip and return the exact JSON body to POST /v1/probe, or undefined when probing was never enabled or there is nothing worth uploading. arrived distinguishes a completed trip from an abandoned one (both apply end suppression).
  • constructor(route_response_json: string, config: any): Create a session from a Valhalla route response JSON string (as returned by the hosted /route API or any Valhalla endpoint). config is optional: { stepAdvanceDistanceM, minimumHorizontalAccuracyM, routeDeviationThresholdM, snapCourseToRoute, waypointAdvanceRangeM }, defaulting to the same values as the mobile SDKs.
  • updateLocation(lat: number, lon: number, timestamp_ms: number, speed_mps?: number | null, course_deg?: number | null, accuracy_m?: number | null): any: Feed a location fix; returns the updated guidance state as { state: "navigating" | "arrived" | "offRoute", … }. timestampMs is milliseconds since the Unix epoch (Date.now()). accuracyM defaults to 0 (trusted exactly) when omitted; pass the platform's reported accuracy so step advance and deviation gating behave correctly.

Example

ts
import init, { GuidanceSession } from "@mapmap/core";

await init();
// A Valhalla route response, from the hosted /route API or any Valhalla server.
const routeJson = await (await fetch("/route.json")).text();
const session = new GuidanceSession(routeJson, { stepAdvanceDistanceM: 20 });
navigator.geolocation.watchPosition((p) => {
  const update = session.updateLocation(p.coords.latitude, p.coords.longitude, p.timestamp, p.coords.speed, p.coords.heading, p.coords.accuracy);
  console.log(update);
});

Class · also exported from @mapmap/core/node

ts
class NavigationController { … }

JavaScript wrapper for NavigationController. This wrapper is required because NavigationController cannot be directly converted to a JavaScript object and requires serialization/deserialization of its methods' inputs and outputs.

Constructor and methods

  • free(): void
  • [Symbol.dispose](): void
  • advanceToNextStep(state: any): any
  • getInitialState(location: any): any
  • constructor(route: any, config: any, should_record: any)
  • updateUserLocation(location: any, state: any): any

Example

ts
import init, { NavigationController, type Route, type SerializableNavigationControllerConfig, type UserLocation } from "@mapmap/core";

await init();
declare const route: Route;           // from RouteAdapter.parseResponse
declare const here: UserLocation;     // the device's latest fix
const config: SerializableNavigationControllerConfig = {
  waypointAdvance: { WaypointWithinRange: 100 },
  stepAdvanceCondition: { DistanceToEndOfStep: { distance: 10, minimumHorizontalAccuracy: 25 } },
  arrivalStepAdvanceCondition: { DistanceToEndOfStep: { distance: 10, minimumHorizontalAccuracy: 25 } },
  routeDeviationTracking: { StaticThreshold: { minimumHorizontalAccuracy: 25, maxAcceptableDeviation: 50 } },
  snappedLocationCourseFiltering: "SnapToRoute",
};
const controller = new NavigationController(route, config, false);
let state = controller.getInitialState(here);
state = controller.updateUserLocation(here, state);
console.log(state);

Class · also exported from @mapmap/core/node

ts
class NavigationReplay { … }

A WebAssembly-compatible wrapper for NavigationReplay that exposes its functionality as a JavaScript object.

This wrapper is required because NavigationReplay cannot be directly converted to a JavaScript object and requires serialization/deserialization of its methods' inputs and outputs.

Constructor and methods

  • free(): void
  • [Symbol.dispose](): void
  • getAllEvents(): any
  • getEventByIndex(current_index: any): any
  • getInitialRoute(): any
  • getInitialTimestamp(): any
  • getTotalDuration(): any
  • constructor(json: string)

Example

ts
import init, { NavigationReplay } from "@mapmap/core";

await init();
declare const recording: string; // NavigationSessionRecording.getRecordingJson()
const replay = new NavigationReplay(recording);
console.log(replay.getTotalDuration(), replay.getAllEvents());

Class · also exported from @mapmap/core/node

ts
class NavigationSession { … }

JavaScript wrapper for NavigationSession (simple version). This wrapper provides basic navigation functionality without observers.

Constructor and methods

  • free(): void
  • [Symbol.dispose](): void
  • advanceToNextStep(state: any): any
  • getInitialState(location: any): any
  • constructor(route: any, config: any)
  • updateUserLocation(location: any, state: any): any

Example

ts
import init, { NavigationSession, type Route, type SerializableNavigationControllerConfig, type UserLocation } from "@mapmap/core";

await init();
declare const route: Route;
declare const config: SerializableNavigationControllerConfig; // as in the NavigationController example
declare const here: UserLocation;
const session = new NavigationSession(route, config);
const state = session.updateUserLocation(here, session.getInitialState(here));
console.log(state);

Class · also exported from @mapmap/core/node

ts
class NavigationSessionRecording { … }

JavaScript wrapper for NavigationSession with recording capabilities. This version includes a NavigationRecorder observer and provides direct access to recording functionality.

Constructor and methods

  • free(): void
  • [Symbol.dispose](): void
  • advanceToNextStep(state: any): any
  • getEvents(): any
  • getInitialState(location: any): any
  • getRecordingJson(): any
  • constructor(route: any, config: any)
  • updateUserLocation(location: any, state: any): any

Example

ts
import init, { NavigationSessionRecording, type Route, type SerializableNavigationControllerConfig, type UserLocation } from "@mapmap/core";

await init();
declare const route: Route;
declare const config: SerializableNavigationControllerConfig;
declare const fixes: UserLocation[];
const session = new NavigationSessionRecording(route, config);
let state = session.getInitialState(fixes[0]);
for (const fix of fixes) state = session.updateUserLocation(fix, state);
const recording: string = session.getRecordingJson(); // replay it with NavigationReplay
console.log(recording.length);

RouteAdapter

Class · also exported from @mapmap/core/node

ts
class RouteAdapter { … }

JavaScript wrapper for RouteAdapter.

Constructor and methods

  • free(): void
  • [Symbol.dispose](): void
  • generateRequest(user_location: any, waypoints: any): any
  • constructor(well_known_route_provider: WellKnownRouteProvider): Creates a new RouteAdapter with a Valhalla HTTP request generator and an OSRM response parser. At the moment, this is the only supported combination.
  • parseResponse(response: Uint8Array): any

Example

ts
import init, { RouteAdapter, type UserLocation, type Waypoint } from "@mapmap/core";

await init();
declare const here: UserLocation;
const adapter = new RouteAdapter({ Valhalla: { endpointUrl: "https://valhalla.example.com/route", profile: "auto" } });
const destination: Waypoint = { coordinate: { lat: 51.4545, lng: -2.5879 }, kind: "Break", properties: undefined };
const request = adapter.generateRequest(here, [destination]);
console.log(request);
// Then send the request, and: adapter.parseResponse(new Uint8Array(await response.arrayBuffer()))

Functions (@mapmap/core)

advanceLocationSimulation, buildOfflineRouteRequest, checkTunnel, default, forbiddenCategories, initSync, locationSimulationFromCoordinates, locationSimulationFromPolyline, locationSimulationFromRoute, parseRouteSummary, polylineDecode, polylineEncode, version

advanceLocationSimulation

Function · also exported from @mapmap/core/node

ts
function advanceLocationSimulation(state: any): any;

JavaScript wrapper for advance_location_simulation.

ParameterTypeDefaultDescription
stateanyrequired

buildOfflineRouteRequest

Function · also exported from @mapmap/core/node

ts
function buildOfflineRouteRequest(locations: any, costing: string, adr_profile: any): string;

Build the Valhalla turn-by-turn request JSON that any Valhalla endpoint (hosted API, self-hosted server, on-device engine) accepts.

locations is an array of { lat, lon } (at least two); costing is a Valhalla costing model ("auto", "truck", "bus", "motor_scooter", "motorcycle", "bicycle", "pedestrian"). An optional ADR profile (truck costing only) is merged into costing_options.truck with the same conflict rules as the hosted gateway and the mobile SDKs, a disagreeing explicit option is an error, never silently overridden.

ParameterTypeDefaultDescription
locationsanyrequired
costingstringrequired
adr_profileanyrequired

Example

ts
import init, { buildOfflineRouteRequest } from "@mapmap/core";

await init();
const body = buildOfflineRouteRequest(
  [{ lat: 51.5072, lon: -0.1276 }, { lat: 51.752, lon: -1.2577 }],
  "truck",
  { heightM: 4.2, hazmat: true, tunnelCode: "C/D" },
);
const response = await fetch("https://valhalla.example.com/route", { method: "POST", body, headers: { "content-type": "application/json" } });
console.log(response.status);

checkTunnel

Function · also exported from @mapmap/core/node

ts
function checkTunnel(profile: any, category: string): any;

Decide whether the vehicle described by profile may pass through a tunnel of ADR category ("A"–"E"), under the conservative worst-case ADR 8.6.4 reading.

profile is a plain object; all fields optional: { heightM, widthM, lengthM, grossWeightT, axleLoadT, axleCount, hazmat, tunnelCode }.

Returns { status: "allowed" } or { status: "blocked", reason }.

ParameterTypeDefaultDescription
profileanyrequired
categorystringrequired

Example

ts
import init, { checkTunnel, forbiddenCategories } from "@mapmap/core";

await init();
const lorry = { heightM: 4.1, grossWeightT: 26, hazmat: true, tunnelCode: "D/E" };
console.log(checkTunnel(lorry, "D")); // { status: "blocked", reason }
console.log(forbiddenCategories(lorry));

default

Function · the default export

ts
function init(module_or_path?: {
    module_or_path: InitInput | Promise<InitInput>;
} | InitInput | Promise<InitInput>): Promise<InitOutput>;

If module_or_path is {RequestInfo} or {URL}, makes a request and for everything else, calls WebAssembly.instantiate directly.

ParameterTypeDefaultDescription
module_or_path?{ module_or_path: InitInput | Promise<InitInput>; } | InitInput | Promise<InitInput>not statedPassing InitInput directly is deprecated.

Options and types: InitInput.

Example

ts
import init, { version } from "@mapmap/core";

// Browser and worker builds: load the WASM once, before any other call.
await init();
console.log(version());

forbiddenCategories

Function · also exported from @mapmap/core/node

ts
function forbiddenCategories(profile: any): string[];

All tunnel categories the vehicle is forbidden from, ascending (e.g. ["C", "D", "E"] for code C). Empty when unrestricted.

ParameterTypeDefaultDescription
profileanyrequired

initSync

Function

ts
function initSync(module: {
    module: SyncInitInput;
} | SyncInitInput): InitOutput;

Instantiates the given module, which can either be bytes or a precompiled WebAssembly.Module.

ParameterTypeDefaultDescription
module{ module: SyncInitInput; } | SyncInitInputrequiredPassing SyncInitInput directly is deprecated.

Options and types: SyncInitInput.

Example

ts
import { initSync, version } from "@mapmap/core";

// When you already hold the WASM bytes (for example in a worker that was sent them).
declare const wasmBytes: ArrayBuffer;
initSync({ module: wasmBytes });
console.log(version());

locationSimulationFromCoordinates

Function · also exported from @mapmap/core/node

ts
function locationSimulationFromCoordinates(coordinates: any, resample_distance: number | null | undefined, bias: LocationBias): any;

JavaScript wrapper for location_simulation_from_coordinates.

ParameterTypeDefaultDescription
coordinatesanyrequired
resample_distancenumber | null | undefinedrequired
biasLocationBiasrequired

Options and types: LocationBias.

locationSimulationFromPolyline

Function · also exported from @mapmap/core/node

ts
function locationSimulationFromPolyline(polyline: string, precision: number, resample_distance: number | null | undefined, bias: LocationBias): any;

JavaScript wrapper for location_simulation_from_polyline.

ParameterTypeDefaultDescription
polylinestringrequired
precisionnumberrequired
resample_distancenumber | null | undefinedrequired
biasLocationBiasrequired

Options and types: LocationBias.

locationSimulationFromRoute

Function · also exported from @mapmap/core/node

ts
function locationSimulationFromRoute(route: any, resample_distance: number | null | undefined, bias: LocationBias): any;

JavaScript wrapper for location_simulation_from_route.

ParameterTypeDefaultDescription
routeanyrequired
resample_distancenumber | null | undefinedrequired
biasLocationBiasrequired

Options and types: LocationBias.

parseRouteSummary

Function · also exported from @mapmap/core/node

ts
function parseRouteSummary(route_response_json: string): any;

Parse a Valhalla route response JSON into an SI summary: { distanceM, durationS, hasToll, hasHighway, hasFerry }.

A Valhalla error body ({"error_code": …}) and malformed JSON both raise with the backend's message.

ParameterTypeDefaultDescription
route_response_jsonstringrequired

Example

ts
import init, { parseRouteSummary } from "@mapmap/core";

await init();
const routeJson = await (await fetch("/route.json")).text();
const { distanceM, durationS, hasToll } = parseRouteSummary(routeJson);
console.log(distanceM, durationS, hasToll);

polylineDecode

Function · also exported from @mapmap/core/node

ts
function polylineDecode(encoded: string, precision: number): Float64Array;

Decode an encoded polyline into a flat Float64Array of [lat0, lon0, lat1, lon1, …] pairs. precision is 5 for OSRM polyline, 6 for Valhalla/OSRM polyline6.

ParameterTypeDefaultDescription
encodedstringrequired
precisionnumberrequired

polylineEncode

Function · also exported from @mapmap/core/node

ts
function polylineEncode(coordinates: Float64Array, precision: number): string;

Encode a flat Float64Array of [lat0, lon0, lat1, lon1, …] pairs as a polyline string at the given precision (5 or 6).

ParameterTypeDefaultDescription
coordinatesFloat64Arrayrequired
precisionnumberrequired

version

Function · also exported from @mapmap/core/node

ts
function version(): string;

The crate version of the underlying navigation core package.

Interfaces (@mapmap/core)

BoundingBox, Congestion, CourseOverGround, GeographicCoordinate, Incident, InitOutput, LaneInfo, LocationSimulationState, NavigationRecordingEvent, OsrmWaypointProperties, Route, RouteStep, SerializableNavigationControllerConfig, SerializableNavState, Speed, SpokenInstruction, TripProgress, TripSummary, UserLocation, ValhallaLocationSearchFilter, ValhallaWaypointProperties, VisualInstruction, VisualInstructionContent, Waypoint

BoundingBox

Interface · also exported from @mapmap/core/node

ts
interface BoundingBox

A geographic bounding box defined by its corners.

PropertyTypeDefaultDescription
swGeographicCoordinaterequiredThe southwest corner of the bounding box.
neGeographicCoordinaterequiredThe northeast corner of the bounding box.

Congestion

Interface · also exported from @mapmap/core/node

ts
interface Congestion

Details about congestion for an incident.

PropertyTypeDefaultDescription
valuenumberrequiredThe level of congestion caused by the incident. 0 = no congestion 100 = road closed Other values mean no congestion was calculated

CourseOverGround

Interface · also exported from @mapmap/core/node

ts
interface CourseOverGround

The direction in which the user/device is observed to be traveling.

PropertyTypeDefaultDescription
degreesnumberrequiredThe direction in which the user's device is traveling, measured in clockwise degrees from true north (N = 0, E = 90, S = 180, W = 270).
accuracynumber | undefinedrequiredThe accuracy of the course value, measured in degrees.

GeographicCoordinate

Interface · also exported from @mapmap/core/node

ts
interface GeographicCoordinate

A geographic coordinate in WGS84.

PropertyTypeDefaultDescription
latnumberrequiredThe latitude (in degrees).
lngnumberrequiredThe Longitude (in degrees).

Incident

Interface · also exported from @mapmap/core/node

ts
interface Incident

An incident affecting the free flow of traffic, such as constructions, accidents, and congestion.

PropertyTypeDefaultDescription
idstringrequiredA unique identifier for the incident.
incidentTypeIncidentTyperequiredThe type of incident.
descriptionstring | undefinedrequiredA short description of the incident.
longDescriptionstring | undefinedrequiredA longer description of the incident.
creationTimeDate | nullrequiredThe time at which the incident was last created. NB: This can change throughout the life of the incident.
startTimeDate | nullrequiredThe time at which the incident started or is expected to start (ex: planned closure).
endTimeDate | nullrequiredThe time at which the incident ended or is expected to end.
impactImpact | undefinedrequiredThe level of impact to traffic.
lanesBlockedBlockedLane[]requiredLanes which are blocked by the incident.
congestionCongestion | undefinedrequiredInfo about the amount of congestion on the road around the incident.
closedboolean | undefinedrequiredIs the road completely closed?
geometryIndexStartnumberrequiredThe index into the RouteStep geometry where the incident starts.
geometryIndexEndnumber | undefinedrequiredThe index into the RouteStep geometry where the incident ends.
subTypestring | undefinedrequiredOptional additional information about the type of incident (free-form text).
subTypeDescriptionstring | undefinedrequiredOptional descriptions about the type of incident (free-form text).
iso31661Alpha2string | undefinedrequiredThe ISO 3166-1 alpha-2 code of the country in which the incident occurs.
iso31661Alpha3string | undefinedrequiredThe ISO 3166-1 alpha-3 code of the country in which the incident occurs.
affectedRoadNamesstring[]requiredA list of road names affected by the incident.
bboxBoundingBox | undefinedrequiredThe bounding box over which the incident occurs.

InitOutput

Interface

ts
interface InitOutput
PropertyTypeDefaultDescription
readonly memoryWebAssembly.Memoryrequired
readonly __wbg_guidancesession_free(a: number, b: number) => voidrequired
readonly buildOfflineRouteRequest(a: number, b: number, c: number, d: number, e: number) => voidrequired
readonly checkTunnel(a: number, b: number, c: number, d: number) => voidrequired
readonly forbiddenCategories(a: number, b: number) => voidrequired
readonly guidancesession_advanceToNextStep(a: number, b: number) => voidrequired
readonly guidancesession_enableProbe(a: number, b: number, c: number) => voidrequired
readonly guidancesession_finishProbeJson(a: number, b: number, c: number, d: number) => voidrequired
readonly guidancesession_new(a: number, b: number, c: number, d: number) => voidrequired
readonly guidancesession_totalSteps(a: number) => numberrequired
readonly guidancesession_updateLocation(a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number, i: number, j: number, k: number) => voidrequired
readonly parseRouteSummary(a: number, b: number, c: number) => voidrequired
readonly polylineDecode(a: number, b: number, c: number, d: number) => voidrequired
readonly polylineEncode(a: number, b: number, c: number, d: number) => voidrequired
readonly version(a: number) => voidrequired
readonly __wbg_navigationcontroller_free(a: number, b: number) => voidrequired
readonly __wbg_navigationreplay_free(a: number, b: number) => voidrequired
readonly __wbg_navigationsession_free(a: number, b: number) => voidrequired
readonly __wbg_navigationsessionrecording_free(a: number, b: number) => voidrequired
readonly __wbg_routeadapter_free(a: number, b: number) => voidrequired
readonly advanceLocationSimulation(a: number) => numberrequired
readonly locationSimulationFromCoordinates(a: number, b: number, c: number, d: number, e: number) => voidrequired
readonly locationSimulationFromPolyline(a: number, b: number, c: number, d: number, e: number, f: number, g: number) => voidrequired
readonly locationSimulationFromRoute(a: number, b: number, c: number, d: number, e: number) => voidrequired
readonly navigationcontroller_advanceToNextStep(a: number, b: number, c: number) => voidrequired
readonly navigationcontroller_getInitialState(a: number, b: number, c: number) => voidrequired
readonly navigationcontroller_new(a: number, b: number, c: number, d: number) => voidrequired
readonly navigationcontroller_updateUserLocation(a: number, b: number, c: number, d: number) => voidrequired
readonly navigationreplay_getAllEvents(a: number, b: number) => voidrequired
readonly navigationreplay_getEventByIndex(a: number, b: number, c: number) => voidrequired
readonly navigationreplay_getInitialRoute(a: number, b: number) => voidrequired
readonly navigationreplay_getInitialTimestamp(a: number, b: number) => voidrequired
readonly navigationreplay_getTotalDuration(a: number, b: number) => voidrequired
readonly navigationreplay_new(a: number, b: number, c: number) => voidrequired
readonly navigationsession_advanceToNextStep(a: number, b: number, c: number) => voidrequired
readonly navigationsession_getInitialState(a: number, b: number, c: number) => voidrequired
readonly navigationsession_new(a: number, b: number, c: number) => voidrequired
readonly navigationsession_updateUserLocation(a: number, b: number, c: number, d: number) => voidrequired
readonly navigationsessionrecording_advanceToNextStep(a: number, b: number, c: number) => voidrequired
readonly navigationsessionrecording_getEvents(a: number, b: number) => voidrequired
readonly navigationsessionrecording_getInitialState(a: number, b: number, c: number) => voidrequired
readonly navigationsessionrecording_getRecordingJson(a: number, b: number) => voidrequired
readonly navigationsessionrecording_new(a: number, b: number, c: number) => voidrequired
readonly navigationsessionrecording_updateUserLocation(a: number, b: number, c: number, d: number) => voidrequired
readonly routeadapter_generateRequest(a: number, b: number, c: number, d: number) => voidrequired
readonly routeadapter_new(a: number, b: number) => voidrequired
readonly routeadapter_parseResponse(a: number, b: number, c: number, d: number) => voidrequired
readonly __wbindgen_export(a: number, b: number) => numberrequired
readonly __wbindgen_export2(a: number, b: number, c: number, d: number) => numberrequired
readonly __wbindgen_export3(a: number) => voidrequired
readonly __wbindgen_add_to_stack_pointer(a: number) => numberrequired
readonly __wbindgen_export4(a: number, b: number, c: number) => voidrequired

LaneInfo

Interface · also exported from @mapmap/core/node

ts
interface LaneInfo

The content of a visual instruction.

PropertyTypeDefaultDescription
activebooleanrequired
directionsstring[]required
activeDirectionstring | undefinedrequired

LocationSimulationState

Interface · also exported from @mapmap/core/node

ts
interface LocationSimulationState

The current state of the simulation.

PropertyTypeDefaultDescription
current_locationUserLocationrequired
remaining_locationsGeographicCoordinate[]required
biasLocationBiasrequired

Interface · also exported from @mapmap/core/node

ts
interface NavigationRecordingEvent

An event that occurs during navigation.

This is used for the optional session recording / telemetry.

PropertyTypeDefaultDescription
timestampnumberrequiredThe timestamp of the event in milliseconds since Jan 1, 1970 UTC.
event_dataNavigationRecordingEventDatarequiredData associated with the event.

OsrmWaypointProperties

Interface · also exported from @mapmap/core/node

ts
interface OsrmWaypointProperties

Waypoint properties parsed from an OSRM-compatible server response.

NOTE: Some servers (such as Valhalla) may support additional parameters at request time which are not echoed back in the response time. This is unfortunate; PRs upstream would likely be welcomed! Similarly, if your server is OSRM-compatible and returns additional attributes, feel free to open a PR to include these as optional properties.

PropertyTypeDefaultDescription
namestring | undefinedrequiredThe name of the street that the waypoint snapped to.
distancenumber | undefinedrequiredThe distance (in meters) between the snapped point and the input coordinate.

Route

Interface · also exported from @mapmap/core/node

ts
interface Route

Information describing the series of steps needed to travel between two or more points.

NOTE: This type is unstable and is still under active development and should be considered unstable.

PropertyTypeDefaultDescription
geometryGeographicCoordinate[]required
bboxBoundingBoxrequired
distancenumberrequiredThe total route distance, in meters.
waypointsWaypoint[]requiredThe ordered list of waypoints to visit, including the starting point. Note that this is distinct from the geometry which includes all points visited. A waypoint represents a start/end point for a route leg.
stepsRouteStep[]required

RouteStep

Interface · also exported from @mapmap/core/node

ts
interface RouteStep

A maneuver (such as a turn or merge) followed by travel of a certain distance until reaching the next step.

PropertyTypeDefaultDescription
geometryGeographicCoordinate[]requiredThe full route geometry for this step.
distancenumberrequiredThe distance, in meters, to travel along the route after the maneuver to reach the next step.
durationnumberrequiredThe estimated duration, in seconds, that it will take to complete this step.
roadNamestring | undefinedrequiredThe name of the road being traveled on (useful for certain UI styles).
exitsstring[]requiredA list of exits (name or number).
instructionstringrequiredA description of the maneuver (ex: "Turn wright onto main street"). Note for UI implementers: the context this appears in (or doesn't) depends somewhat on your use case and routing engine. For example, this field is useful as a written instruction in Valhalla.
visualInstructionsVisualInstruction[]requiredA list of instructions for visual display (usually as banners) at specific points along the step.
spokenInstructionsSpokenInstruction[]requiredA list of prompts to announce (via speech synthesis) at specific points along the step.
annotationsstring[] | undefinedrequiredA list of json encoded strings representing annotations between each coordinate along the step.
incidentsIncident[]requiredA list of incidents that occur along the step.
drivingSideDrivingSide | undefinedrequiredWhich side of the road traffic drives on for this step. This is relevant for roundabouts: left-hand traffic (e.g. UK) uses clockwise roundabouts, while right-hand traffic uses counterclockwise roundabouts.
roundaboutExitNumbernumber | undefinedrequiredThe exit number when entering a roundabout (1 = first exit, 2 = second, etc.).

SerializableNavigationControllerConfig

Interface · also exported from @mapmap/core/node

ts
interface SerializableNavigationControllerConfig
PropertyTypeDefaultDescription
waypointAdvanceWaypointAdvanceModerequiredConfigures when navigation advances to the next waypoint in the route.
stepAdvanceConditionSerializableStepAdvanceConditionrequiredConfigures when navigation advances to the next step in the route.
arrivalStepAdvanceConditionSerializableStepAdvanceConditionrequiredA special advance condition used for the final 2 route steps (last and arrival). This exists because several of our step advance conditions require entry and exit from a step's geometry. The end of the route/arrival doesn't always accommodate the expected location updates for the core step advance condition.
routeDeviationTrackingRouteDeviationTrackingrequiredConfigures when the user is deemed to be off course. NOTE: This is distinct from the action that is taken. It is only the determination that the user has deviated from the expected route.
snappedLocationCourseFilteringCourseFilteringrequiredConfigures how the heading component of the snapped location is reported in TripState.

SerializableNavState

Interface · also exported from @mapmap/core/node

ts
interface SerializableNavState
PropertyTypeDefaultDescription
tripStateTripStaterequired
stepAdvanceConditionSerializableStepAdvanceConditionrequired

Speed

Interface · also exported from @mapmap/core/node

ts
interface Speed

The speed of the user from the location provider.

PropertyTypeDefaultDescription
valuenumberrequiredThe user's speed in meters per second.
accuracynumber | undefinedrequiredThe accuracy of the speed value, measured in meters per second.

SpokenInstruction

Interface · also exported from @mapmap/core/node

ts
interface SpokenInstruction

An instruction that can be synthesized using a TTS engine to announce an upcoming maneuver.

Note that these do not have any locale information attached.

PropertyTypeDefaultDescription
textstringrequiredPlain-text instruction which can be synthesized with a TTS engine.
ssmlstring | undefinedrequiredSpeech Synthesis Markup Language, which should be preferred by clients capable of understanding it.
triggerDistanceBeforeManeuvernumberrequiredHow far (in meters) from the upcoming maneuver the instruction should start being spoken.
utteranceIdstringrequiredA unique identifier for this instruction. This is provided so that platform-layer integrations can easily disambiguate between distinct utterances, which may have the same textual content. UUIDs conveniently fill this purpose. NOTE: While it is possible to deterministically create UUIDs, we do not do so at this time. This should be theoretically possible though if someone cares to write up a proposal and a PR.

TripProgress

Interface · also exported from @mapmap/core/node

ts
interface TripProgress

High-level state describing progress through a route.

PropertyTypeDefaultDescription
distanceToNextManeuvernumberrequiredThe distance to the next maneuver, in meters.
distanceRemainingnumberrequiredThe total distance remaining in the trip, in meters. This is the sum of the distance remaining in the current step and the distance remaining in all subsequent steps.
durationRemainingnumberrequiredThe total duration remaining in the trip, in seconds.

TripSummary

Interface · also exported from @mapmap/core/node

ts
interface TripSummary

Information pertaining to the user's full navigation trip. This includes simple stats like total duration and distance.

PropertyTypeDefaultDescription
distanceTravelednumberrequiredThe total raw distance traveled in the trip, in meters.
snappedDistanceTravelednumberrequiredThe total snapped distance traveled in the trip, in meters.
startedAtDaterequiredWhen the trip was started.
endedAtDate | nullrequiredWhen the trip was completed or canceled.

UserLocation

Interface · also exported from @mapmap/core/node

ts
interface UserLocation

The location of the user that is navigating.

In addition to coordinates, this includes estimated accuracy and course information, which can influence navigation logic and UI.

NOTE: Heading is absent on purpose. Heading updates are not related to a change in the user's location.

PropertyTypeDefaultDescription
coordinatesGeographicCoordinaterequired
horizontalAccuracynumberrequiredThe estimated accuracy of the coordinate (in meters)
courseOverGroundCourseOverGround | undefinedrequired
timestamp{ secs_since_epoch: number; nanos_since_epoch: number; }required
speedSpeed | undefinedrequired

ValhallaLocationSearchFilter

Interface · also exported from @mapmap/core/node

ts
interface ValhallaLocationSearchFilter

A set of optional filters to exclude candidate edges based on their attributes.

PropertyTypeDefaultDescription
exclude_tunnel?booleannot statedWhether to exclude roads marked as tunnels.
exclude_bridge?booleannot statedWhether to exclude roads marked as bridges.
exclude_tolls?booleannot statedWhether to exclude roads with tolls.
exclude_ferry?booleannot statedWhether to exclude ferries.
exclude_ramp?booleannot statedWhether to exclude roads marked as ramps.
exclude_closures?booleannot statedWhether to exclude roads marked as closed due to a live traffic closure.
min_road_class?ValhallaRoadClassnot statedThe lowest road class allowed.
max_road_class?ValhallaRoadClassnot statedThe highest road class allowed.
level?numbernot statedIf specified, will only consider edges that are on or traverse the passed floor level. It will set search_cutoff to a default value of 300 meters if no cutoff value is passed. Additionally, if a search_cutoff is passed, it will be clamped to 1000 meters.

ValhallaWaypointProperties

Interface · also exported from @mapmap/core/node

ts
interface ValhallaWaypointProperties

Waypoint properties supported by Valhalla servers.

Our docstrings are short here, since Valhalla is the final authority. Refer to https://valhalla.github.io/valhalla/api/turn-by-turn/api-reference/#locations for more details, including default values. Other Valhalla-based APIs such as Stadia Maps or Mapbox may have slightly different defaults. Refer to your vendor's documentation when in doubt.

NOTE: Waypoint properties will NOT currently be echoed back in OSRM format, so these are sent to the server one time.

PropertyTypeDefaultDescription
headingnumber | undefinedrequiredPreferred direction of travel for the start from the location. The heading is indicated in degrees from north in a clockwise direction, where north is 0°, east is 90°, south is 180°, and west is 270°. Avoid specifying this unless you really know what you're doing. Most use cases for this are better served by preferred_side.
heading_tolerancenumber | undefinedrequiredHow close in degrees a given street's angle must be in order for it to be considered as in the same direction of the heading parameter.
minimum_reachabilitynumber | undefinedrequiredMinimum number of nodes (intersections) reachable for a given edge (road between intersections) to consider that edge as belonging to a connected region. Disconnected edges are ignored.
radiusnumber | undefinedrequiredThe number of meters about this input location within which edges will be considered as candidates for said location. If there are no candidates within this distance, it will return the closest candidate within reason. This allows the routing engine to match another edge which is NOT the closest to your location, but in within this range. This can be useful if you have other constraints and want to disambiguate, but beware that this can lead to very strange results, particularly if you have specified other parameters like heading. This is an advanced feature and should only be used with extreme care.
preferred_sideValhallaWaypointPreferredSide | undefinedrequiredDetermines whether the location should be visited from the same, opposite or either side of the road, with respect to the side of the road the given locale drives on. NOTE: If the location is not offset from the road centerline or is very close to an intersection, this option has no effect!
display_coordinateGeographicCoordinate | undefinedrequiredLatitude of the map location in degrees. If provided, the waypoint location will still be used for routing, but these coordinates will determine the side of the street.
search_cutoffnumber | undefinedrequiredThe cutoff at which we will assume the input is too far away from civilization to be worth correlating to the nearest graph elements.
node_snap_tolerancenumber | undefinedrequiredDuring edge correlation, this is the tolerance used to determine whether to snap to the intersection rather than along the street. If the snap location is within this distance from the intersection, the intersection is used instead.
street_side_tolerancenumber | undefinedrequiredA tolerance in meters from the edge centerline used for determining the side of the street that the location is on. If the distance to the centerline is less than this tolerance, no side will be inferred. Otherwise, the left or right side will be selected depending on the direction of travel.
street_side_max_distancenumber | undefinedrequiredThe max distance in meters that the input coordinates or display lat/lon can be from the edge centerline for them to be used for determining the side of the street. Beyond this distance, no street side is inferred.
street_side_cutoffValhallaRoadClass | undefinedrequiredDisables the preferred_side when set to same or opposite if the edge has a road class less than that provided by street_side_cutoff.
search_filterValhallaLocationSearchFilter | undefinedrequiredA set of optional filters to exclude candidate edges based on their attributes.
allow_uturnsboolean | undefinedtrueDetermines whether U-Turns are allowed at the waypoint (if it is an intermediate waypoint, not the first or last). Defaults to true. This has the effect of converting a WaypointKind::Break into a Valhalla break_through, and a WaypointKind::Via into a through.
waypoint_namestring | undefinedrequiredLocation or business name. The name may be used in the route narration directions, such as "You have arrived at <business name>.\ WARNING: this param is not echoed back in the response, so this can disappear when rerouting! NOTE: Serialized as waypoint_name in the waypoint properties blob so it cannot collide with the name of OsrmWaypointProperties (the snapped street name), which occupies the same blob on waypoints rebuilt from a route response (e.g. the remaining waypoints used for reroute requests). It is still sent to Valhalla as name.

VisualInstruction

Interface · also exported from @mapmap/core/node

ts
interface VisualInstruction

An instruction for visual display (usually as banners) at a specific point along a RouteStep.

PropertyTypeDefaultDescription
primaryContentVisualInstructionContentrequiredThe primary instruction content. This is usually given more visual weight.
secondaryContentVisualInstructionContent | undefinedrequiredOptional secondary instruction content.
subContentVisualInstructionContent | undefinedrequiredOptional sub-maneuver instruction content.
triggerDistanceBeforeManeuvernumberrequiredHow far (in meters) from the upcoming maneuver the instruction should start being displayed

VisualInstructionContent

Interface · also exported from @mapmap/core/node

ts
interface VisualInstructionContent

The content of a visual instruction.

PropertyTypeDefaultDescription
textstringrequiredThe text to display.
maneuverTypeManeuverType | undefinedrequiredA standardized maneuver type (if any).
maneuverModifierManeuverModifier | undefinedrequiredA standardized maneuver modifier (if any).
roundaboutExitDegreesnumber | undefinedrequiredIf applicable, the number of degrees you need to go around the roundabout before exiting. For example, entering and exiting the roundabout in the same direction of travel (as if you had gone straight, apart from the detour) would be an exit angle of 180 degrees.
laneInfoLaneInfo[] | undefinedrequiredDetailed information about the lanes. This is typically only present in sub-maneuver instructions.
exitNumbersstring[]requiredThe exit number (or similar identifier like "8B").

Waypoint

Interface · also exported from @mapmap/core/node

ts
interface Waypoint

A waypoint along a route.

Within the context of Ferrostar, a route request consists of exactly one UserLocation and at least one Waypoint. The route starts from the user's location (which may contain other useful information like their current course for the crate::routing_adapters::RouteRequestGenerator to use) and proceeds through one or more waypoints.

Waypoints are used during route calculation, are tracked throughout the lifecycle of a trip, and are used for recalculating when the user deviates from the expected route.

Note that support for properties beyond basic geographic coordinates varies by routing engine.

PropertyTypeDefaultDescription
coordinateGeographicCoordinaterequired
kindWaypointKindrequired
propertiesnumber[] | undefinedrequiredOptional additional properties that will be passed on to the crate::routing_adapters::RouteRequestGenerator. Most users should prefer convenience functions like Waypoint::new_with_valhalla_properties (or, on platforms like iOS and Android with UniFFI bindings, crate::routing_adapters::valhalla::create_waypoint_with_valhalla_properties). # Format guidelines This MAY be any format agreed upon by both the request generator and response parser. However, to promote interoperability, all implementations in the Ferrostar codebase MUST use JSON. We selected JSON is selected not because it is good, but because generics (i.e., becoming Waypoint<T>, where an example T is ValhallaProperties) would be way too painful, particularly for foreign code. Especially JavaScript. In any case, crate::routing_adapters::RouteRequestGenerator and crate::routing_adapters::RouteResponseParser implementations SHOULD document their level support for this, ideally with an exportable record type.

Types (@mapmap/core)

BlockedLane, CourseFiltering, DeviationCalculationPolicy, DeviationKind, DrivingSide, GraphHopperVoiceUnits, Impact, IncidentType, InitInput, LocationBias, ManeuverModifier, ManeuverType, NavigationRecordingEventData, RouteDeviation, RouteDeviationTracking, SerializableStepAdvanceCondition, SimulationError, SyncInitInput, TripState, ValhallaRoadClass, ValhallaWaypointPreferredSide, WaypointAdvanceMode, WaypointKind, WellKnownRouteProvider

BlockedLane

Type · also exported from @mapmap/core/node

ts
type BlockedLane = "left" | "left center" | "left turn lane" | "center" | "right" | "right center" | "right turn lane" | "hov";

The lane type blocked by the incident.

CourseFiltering

Type · also exported from @mapmap/core/node

ts
type CourseFiltering = "SnapToRoute" | "Raw";

Controls filtering/post-processing of user course by the NavigationController.

DeviationCalculationPolicy

Type · also exported from @mapmap/core/node

ts
type DeviationCalculationPolicy = "Always" | "WhileOnRoute" | "WhileOnCurrentStep";

Controls when a deviation-aware step-advance condition is allowed to evaluate, based on the user's current RouteDeviation status.

DeviationKind

Type · also exported from @mapmap/core/node

ts
type DeviationKind = {
    OffStepOnRoute: {
        deviationFromStepLine: number;
    };
} | {
    CompletelyOffRoute: {
        deviationFromRouteLine: number;
    };
};

The kind of deviation from the expected route.

DrivingSide

Type · also exported from @mapmap/core/node

ts
type DrivingSide = "left" | "right";

Which side of the road traffic drives on.

This is needed by consumers like Android Auto to determine whether a roundabout should be rendered as clockwise (right-hand traffic) or counterclockwise (left-hand traffic).

GraphHopperVoiceUnits

Type · also exported from @mapmap/core/node

ts
type GraphHopperVoiceUnits = "metric" | "imperial";

Impact

Type · also exported from @mapmap/core/node

ts
type Impact = "unknown" | "critical" | "major" | "minor" | "low";

The impact of the incident that has occurred.

IncidentType

Type · also exported from @mapmap/core/node

ts
type IncidentType = "accident" | "congestion" | "construction" | "disabled_vehicle" | "lane_restriction" | "mass_transit" | "miscellaneous" | "other_news" | "planned_event" | "road_closure" | "road_hazard" | "weather";

The type of incident that has occurred.

InitInput

Type

ts
type InitInput = RequestInfo | URL | Response | BufferSource | WebAssembly.Module;

LocationBias

Type · also exported from @mapmap/core/node

ts
type LocationBias = {
    Left: number;
} | {
    Right: number;
} | {
    Random: number;
} | "None";

Controls how simulated locations deviate from the actual route line. This simulates real-world GPS behavior where readings often have systematic bias.

ManeuverModifier

Type · also exported from @mapmap/core/node

ts
type ManeuverModifier = "uturn" | "sharp right" | "right" | "slight right" | "straight" | "slight left" | "left" | "sharp left";

Additional information to further specify a ManeuverType.

ManeuverType

Type · also exported from @mapmap/core/node

ts
type ManeuverType = "turn" | "new name" | "depart" | "arrive" | "merge" | "on ramp" | "off ramp" | "fork" | "end of road" | "continue" | "roundabout" | "rotary" | "roundabout turn" | "notification" | "exit roundabout" | "exit rotary";

The broad class of maneuver to perform.

This is usually combined with ManeuverModifier in VisualInstructionContent.

Type · also exported from @mapmap/core/node

ts
type NavigationRecordingEventData = {
    StateUpdate: {
        trip_state: TripState;
        step_advance_condition: SerializableStepAdvanceCondition;
    };
} | {
    RouteUpdate: {
        route: Route;
    };
};

The event type.

For full replayability, we record things like rerouting, and not just location updates.

RouteDeviation

Type · also exported from @mapmap/core/node

ts
type RouteDeviation = "NoDeviation" | {
    Deviation: {
        kind: DeviationKind;
    };
};

Status information that describes whether the user is proceeding according to the route or not.

Note that the name is intentionally a bit generic to allow for expansion of other states. For example, we could conceivably add a "wrong way" status in the future.

RouteDeviationTracking

Type · also exported from @mapmap/core/node

ts
type RouteDeviationTracking = "None" | {
    StaticThreshold: {
        minimumHorizontalAccuracy: number;
        maxAcceptableDeviation: number;
    };
};

Determines if the user has deviated from the expected route.

SerializableStepAdvanceCondition

Type · also exported from @mapmap/core/node

ts
type SerializableStepAdvanceCondition = "Manual" | {
    DistanceToEndOfStep: {
        distance: number;
        minimumHorizontalAccuracy: number;
    };
} | {
    DistanceFromStep: {
        distance: number;
        minimumHorizontalAccuracy: number;
        calculationPolicy: DeviationCalculationPolicy;
    };
} | {
    DistanceEntryExit: {
        distanceToEndOfStep: number;
        distanceAfterEndStep: number;
        minimumHorizontalAccuracy: number;
        hasReachedEndOfCurrentStep: boolean;
    };
} | {
    DistanceEntryAndSnappedExit: {
        distanceToEndOfStep: number;
        distanceAfterEndStep: number;
        minimumHorizontalAccuracy: number;
        hasReachedEndOfCurrentStep: boolean;
    };
} | {
    OrAdvanceConditions: {
        conditions: SerializableStepAdvanceCondition[];
    };
} | {
    AndAdvanceConditions: {
        conditions: SerializableStepAdvanceCondition[];
    };
};

SimulationError

Type · also exported from @mapmap/core/node

ts
type SimulationError = {
    PolylineError: {
        error: string;
    };
} | "NotEnoughPoints";

SyncInitInput

Type

ts
type SyncInitInput = BufferSource | WebAssembly.Module;

TripState

Type · also exported from @mapmap/core/node

ts
type TripState = {
    Idle: {
        user_location: UserLocation | undefined;
    };
} | {
    Navigating: {
        currentStepGeometryIndex: number | undefined;
        userLocation: UserLocation;
        snappedUserLocation: UserLocation;
        remainingSteps: RouteStep[];
        remainingWaypoints: Waypoint[];
        progress: TripProgress;
        summary: TripSummary;
        deviation: RouteDeviation;
        visualInstruction: VisualInstruction | undefined;
        spokenInstruction: SpokenInstruction | undefined;
        annotationJson: string | undefined;
    };
} | {
    Complete: {
        user_location: UserLocation;
        summary: TripSummary;
    };
};

The state of a navigation session.

This is produced by NavigationController methods including get_initial_state and update_user_location.

ValhallaRoadClass

Type · also exported from @mapmap/core/node

ts
type ValhallaRoadClass = "motorway" | "trunk" | "primary" | "secondary" | "tertiary" | "unclassified" | "residential" | "service_other";

A road class in the Valhalla taxonomy.

These are ordered from highest (fastest travel speed) to lowest.

ValhallaWaypointPreferredSide

Type · also exported from @mapmap/core/node

ts
type ValhallaWaypointPreferredSide = "same" | "opposite" | "either";

Specifies a preferred side for departing from / arriving at a location.

Examples:

  • Germany drives on the right side of the road. A value of same will only allow leaving or arriving at a location such that it is on your right.
  • Australia drives on the left side of the road. Passing a value of same will only allow leaving or arriving at a location such that it is on your left.

WaypointAdvanceMode

Type · also exported from @mapmap/core/node

ts
type WaypointAdvanceMode = {
    WaypointWithinRange: number;
} | {
    WaypointAlongAdvancingStep: number;
};

Controls when a waypoint should be marked as complete.

While a route may consist of thousands of points, waypoints are special. A simple trip will have only one waypoint: the final destination. A more complex trip may have several intermediate stops. Just as the navigation state keeps track of which steps remain in the route, it also tracks which waypoints are still remaining.

Tracking waypoints enables Ferrostar to reroute users when they stray off the route line. The waypoint advance mode specifies how the framework decides that a waypoint has been visited (and is removed from the list).

NOTE: Advancing to the next step and advancing to the next waypoint are separate processes. This will not normally cause any issues, but keep in mind that manually advancing to the next step does not necessarily imply that the waypoint will be marked as complete!

WaypointKind

Type · also exported from @mapmap/core/node

ts
type WaypointKind = "Break" | "Via";

Describes characteristics of the waypoint for routing purposes.

WellKnownRouteProvider

Type · also exported from @mapmap/core/node

ts
type WellKnownRouteProvider = {
    Valhalla: {
        endpointUrl: string;
        profile: string;
        optionsJson?: string | undefined;
    };
} | {
    GraphHopper: {
        endpointUrl: string;
        profile: string;
        locale: string;
        voiceUnits: GraphHopperVoiceUnits;
        optionsJson?: string | undefined;
    };
};

Configurations for built-in route providers.

@mapmap/core/node

ts
import { /* … */ } from "@mapmap/core/node";

Every export of this entry point is documented above, under @mapmap/core: 62 names, that is all of them except default, InitInput, InitOutput, initSync, SyncInitInput.