UNPKG

@stadiamaps/ferrostar

Version:

The core of modern turn-by-turn navigation.

879 lines (826 loc) 31.2 kB
/* tslint:disable */ /* eslint-disable */ /** * A geographic bounding box defined by its corners. */ export interface BoundingBox { /** * The southwest corner of the bounding box. */ sw: GeographicCoordinate; /** * The northeast corner of the bounding box. */ ne: GeographicCoordinate; } /** * The lane type blocked by the incident. */ export type BlockedLane = "left" | "left center" | "left turn lane" | "center" | "right" | "right center" | "right turn lane" | "hov"; /** * 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. */ export interface SpokenInstruction { /** * Plain-text instruction which can be synthesized with a TTS engine. */ text: string; /** * Speech Synthesis Markup Language, which should be preferred by clients capable of understanding it. */ ssml: string | undefined; /** * How far (in meters) from the upcoming maneuver the instruction should start being spoken. */ triggerDistanceBeforeManeuver: number; /** * A 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. */ utteranceId: string; } /** * Details about congestion for an incident. */ export interface Congestion { /** * The level of congestion caused by the incident. * * 0 = no congestion * * 100 = road closed * * Other values mean no congestion was calculated */ value: number; } /** * The type of incident that has occurred. */ export type IncidentType = "accident" | "congestion" | "construction" | "disabled_vehicle" | "lane_restriction" | "mass_transit" | "miscellaneous" | "other_news" | "planned_event" | "road_closure" | "road_hazard" | "weather"; /** * 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). */ export type DrivingSide = "left" | "right"; /** * A maneuver (such as a turn or merge) followed by travel of a certain distance until reaching * the next step. */ export interface RouteStep { /** * The full route geometry for this step. */ geometry: GeographicCoordinate[]; /** * The distance, in meters, to travel along the route after the maneuver to reach the next step. */ distance: number; /** * The estimated duration, in seconds, that it will take to complete this step. */ duration: number; /** * The name of the road being traveled on (useful for certain UI styles). */ roadName: string | undefined; /** * A list of exits (name or number). */ exits: string[]; /** * A 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. */ instruction: string; /** * A list of instructions for visual display (usually as banners) at specific points along the step. */ visualInstructions: VisualInstruction[]; /** * A list of prompts to announce (via speech synthesis) at specific points along the step. */ spokenInstructions: SpokenInstruction[]; /** * A list of json encoded strings representing annotations between each coordinate along the step. */ annotations: string[] | undefined; /** * A list of incidents that occur along the step. */ incidents: Incident[]; /** * Which 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. */ drivingSide: DrivingSide | undefined; /** * The exit number when entering a roundabout (1 = first exit, 2 = second, etc.). */ roundaboutExitNumber: number | undefined; } /** * 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. */ export interface Route { geometry: GeographicCoordinate[]; bbox: BoundingBox; /** * The total route distance, in meters. */ distance: number; /** * The 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. */ waypoints: Waypoint[]; steps: RouteStep[]; } /** * The broad class of maneuver to perform. * * This is usually combined with [`ManeuverModifier`] in [`VisualInstructionContent`]. */ export 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"; /** * A geographic coordinate in WGS84. */ export interface GeographicCoordinate { /** * The latitude (in degrees). */ lat: number; /** * The Longitude (in degrees). */ lng: number; } /** * The content of a visual instruction. */ export interface LaneInfo { active: boolean; directions: string[]; activeDirection: string | undefined; } /** * The speed of the user from the location provider. */ export interface Speed { /** * The user\'s speed in meters per second. */ value: number; /** * The accuracy of the speed value, measured in meters per second. */ accuracy: number | undefined; } /** * The direction in which the user/device is observed to be traveling. */ export interface CourseOverGround { /** * The direction in which the user\'s device is traveling, measured in clockwise degrees from * true north (N = 0, E = 90, S = 180, W = 270). */ degrees: number; /** * The accuracy of the course value, measured in degrees. */ accuracy: number | undefined; } /** * An incident affecting the free flow of traffic, * such as constructions, accidents, and congestion. */ export interface Incident { /** * A unique identifier for the incident. */ id: string; /** * The type of incident. */ incidentType: IncidentType; /** * A short description of the incident. */ description: string | undefined; /** * A longer description of the incident. */ longDescription: string | undefined; /** * The time at which the incident was *last* created. * * NB: This can change throughout the life of the incident. */ creationTime: Date | null; /** * The time at which the incident started or is expected to start (ex: planned closure). */ startTime: Date | null; /** * The time at which the incident ended or is expected to end. */ endTime: Date | null; /** * The level of impact to traffic. */ impact: Impact | undefined; /** * Lanes which are blocked by the incident. */ lanesBlocked: BlockedLane[]; /** * Info about the amount of congestion on the road around the incident. */ congestion: Congestion | undefined; /** * Is the road completely closed? */ closed: boolean | undefined; /** * The index into the [`RouteStep`] geometry where the incident starts. */ geometryIndexStart: number; /** * The index into the [`RouteStep`] geometry where the incident ends. */ geometryIndexEnd: number | undefined; /** * Optional additional information about the type of incident (free-form text). */ subType: string | undefined; /** * Optional descriptions about the type of incident (free-form text). */ subTypeDescription: string | undefined; /** * The ISO 3166-1 alpha-2 code of the country in which the incident occurs. */ iso31661Alpha2: string | undefined; /** * The ISO 3166-1 alpha-3 code of the country in which the incident occurs. */ iso31661Alpha3: string | undefined; /** * A list of road names affected by the incident. */ affectedRoadNames: string[]; /** * The bounding box over which the incident occurs. */ bbox: BoundingBox | undefined; } /** * The impact of the incident that has occurred. */ export type Impact = "unknown" | "critical" | "major" | "minor" | "low"; /** * An instruction for visual display (usually as banners) at a specific point along a [`RouteStep`]. */ export interface VisualInstruction { /** * The primary instruction content. * * This is usually given more visual weight. */ primaryContent: VisualInstructionContent; /** * Optional secondary instruction content. */ secondaryContent: VisualInstructionContent | undefined; /** * Optional sub-maneuver instruction content. */ subContent: VisualInstructionContent | undefined; /** * How far (in meters) from the upcoming maneuver the instruction should start being displayed */ triggerDistanceBeforeManeuver: number; } /** * Additional information to further specify a [`ManeuverType`]. */ export type ManeuverModifier = "uturn" | "sharp right" | "right" | "slight right" | "straight" | "slight left" | "left" | "sharp left"; /** * 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. */ export interface UserLocation { coordinates: GeographicCoordinate; /** * The estimated accuracy of the coordinate (in meters) */ horizontalAccuracy: number; courseOverGround: CourseOverGround | undefined; timestamp: { secs_since_epoch: number; nanos_since_epoch: number }; speed: Speed | undefined; } /** * 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. */ export interface Waypoint { coordinate: GeographicCoordinate; kind: WaypointKind; /** * Optional 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. */ properties: number[] | undefined; } /** * The content of a visual instruction. */ export interface VisualInstructionContent { /** * The text to display. */ text: string; /** * A standardized maneuver type (if any). */ maneuverType: ManeuverType | undefined; /** * A standardized maneuver modifier (if any). */ maneuverModifier: ManeuverModifier | undefined; /** * If 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. */ roundaboutExitDegrees: number | undefined; /** * Detailed information about the lanes. This is typically only present in sub-maneuver instructions. */ laneInfo: LaneInfo[] | undefined; /** * The exit number (or similar identifier like \"8B\"). */ exitNumbers: string[]; } /** * Describes characteristics of the waypoint for routing purposes. */ export type WaypointKind = "Break" | "Via"; /** * Configurations for built-in route providers. */ export type WellKnownRouteProvider = { Valhalla: { endpointUrl: string; profile: string; optionsJson?: string | undefined } } | { GraphHopper: { endpointUrl: string; profile: string; locale: string; voiceUnits: GraphHopperVoiceUnits; optionsJson?: string | undefined } }; /** * An event that occurs during navigation. * * This is used for the optional session recording / telemetry. */ export interface NavigationRecordingEvent { /** * The timestamp of the event in milliseconds since Jan 1, 1970 UTC. */ timestamp: number; /** * Data associated with the event. */ event_data: NavigationRecordingEventData; } /** * The event type. * * For full replayability, we record things like rerouting, and not just location updates. */ export type NavigationRecordingEventData = { StateUpdate: { trip_state: TripState; step_advance_condition: SerializableStepAdvanceCondition } } | { RouteUpdate: { route: Route } }; export type SimulationError = { PolylineError: { error: string } } | "NotEnoughPoints"; /** * Controls how simulated locations deviate from the actual route line. * This simulates real-world GPS behavior where readings often have systematic bias. */ export type LocationBias = { Left: number } | { Right: number } | { Random: number } | "None"; /** * The current state of the simulation. */ export interface LocationSimulationState { current_location: UserLocation; remaining_locations: GeographicCoordinate[]; bias: LocationBias; } /** * 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. */ export type ValhallaWaypointPreferredSide = "same" | "opposite" | "either"; /** * A set of optional filters to exclude candidate edges based on their attributes. */ export interface ValhallaLocationSearchFilter { /** * Whether to exclude roads marked as tunnels. */ exclude_tunnel?: boolean; /** * Whether to exclude roads marked as bridges. */ exclude_bridge?: boolean; /** * Whether to exclude roads with tolls. */ exclude_tolls?: boolean; /** * Whether to exclude ferries. */ exclude_ferry?: boolean; /** * Whether to exclude roads marked as ramps. */ exclude_ramp?: boolean; /** * Whether to exclude roads marked as closed due to a live traffic closure. */ exclude_closures?: boolean; /** * The lowest road class allowed. */ min_road_class?: ValhallaRoadClass; /** * The highest road class allowed. */ max_road_class?: ValhallaRoadClass; /** * If 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. */ level?: number; } /** * A road class in the Valhalla taxonomy. * * These are ordered from highest (fastest travel speed) to lowest. */ export type ValhallaRoadClass = "motorway" | "trunk" | "primary" | "secondary" | "tertiary" | "unclassified" | "residential" | "service_other"; /** * 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. */ export interface ValhallaWaypointProperties { /** * Preferred 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: number | undefined; /** * How 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. */ heading_tolerance: number | undefined; /** * Minimum 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. */ minimum_reachability: number | undefined; /** * The 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. */ radius: number | undefined; /** * Determines 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! */ preferred_side: ValhallaWaypointPreferredSide | undefined; /** * Latitude 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. */ display_coordinate: GeographicCoordinate | undefined; /** * The cutoff at which we will assume the input is too far away from civilization * to be worth correlating to the nearest graph elements. */ search_cutoff: number | undefined; /** * During 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. */ node_snap_tolerance: number | undefined; /** * A 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_tolerance: number | undefined; /** * The 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_max_distance: number | undefined; /** * Disables the `preferred_side` when set to `same` or `opposite` * if the edge has a road class less than that provided by `street_side_cutoff`. */ street_side_cutoff: ValhallaRoadClass | undefined; /** * A set of optional filters to exclude candidate edges based on their attributes. */ search_filter: ValhallaLocationSearchFilter | undefined; /** * Determines 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`. */ allow_uturns: boolean | undefined; } /** * 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. */ export interface OsrmWaypointProperties { /** * The name of the street that the waypoint snapped to. */ name: string | undefined; /** * The distance (in meters) between the snapped point and the input coordinate. */ distance: number | undefined; } /** * 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. */ export type RouteDeviation = "NoDeviation" | { OffRoute: { deviationFromRouteLine: number } }; /** * Determines if the user has deviated from the expected route. */ export type RouteDeviationTracking = "None" | { StaticThreshold: { minimumHorizontalAccuracy: number; maxAcceptableDeviation: number } }; export type SerializableStepAdvanceCondition = "Manual" | { DistanceToEndOfStep: { distance: number; minimumHorizontalAccuracy: number } } | { DistanceFromStep: { distance: number; minimumHorizontalAccuracy: number; calculateWhileOffRoute: boolean } } | { DistanceEntryExit: { distanceToEndOfStep: number; distanceAfterEndStep: number; minimumHorizontalAccuracy: number; hasReachedEndOfCurrentStep: boolean } } | { DistanceEntryAndSnappedExit: { distanceToEndOfStep: number; distanceAfterEndStep: number; minimumHorizontalAccuracy: number; hasReachedEndOfCurrentStep: boolean } } | { OrAdvanceConditions: { conditions: SerializableStepAdvanceCondition[] } } | { AndAdvanceConditions: { conditions: SerializableStepAdvanceCondition[] } }; export type GraphHopperVoiceUnits = "metric" | "imperial"; export interface SerializableNavState { tripState: TripState; stepAdvanceCondition: SerializableStepAdvanceCondition; } /** * Controls filtering/post-processing of user course by the [`NavigationController`]. */ export type CourseFiltering = "SnapToRoute" | "Raw"; /** * High-level state describing progress through a route. */ export interface TripProgress { /** * The distance to the next maneuver, in meters. */ distanceToNextManeuver: number; /** * The 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. */ distanceRemaining: number; /** * The total duration remaining in the trip, in seconds. */ durationRemaining: number; } /** * The state of a navigation session. * * This is produced by [`NavigationController`](super::NavigationController) methods * including [`get_initial_state`](super::NavigationController::get_initial_state) * and [`update_user_location`](super::NavigationController::update_user_location). */ export 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 } }; /** * 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! */ export type WaypointAdvanceMode = { WaypointWithinRange: number } | { WaypointAlongAdvancingStep: number }; /** * Information pertaining to the user\'s full navigation trip. This includes * simple stats like total duration and distance. */ export interface TripSummary { /** * The total raw distance traveled in the trip, in meters. */ distanceTraveled: number; /** * The total snapped distance traveled in the trip, in meters. */ snappedDistanceTraveled: number; /** * When the trip was started. */ startedAt: Date; /** * When the trip was completed or canceled. */ endedAt: Date | null; } export interface SerializableNavigationControllerConfig { /** * Configures when navigation advances to the next waypoint in the route. */ waypointAdvance: WaypointAdvanceMode; /** * Configures when navigation advances to the next step in the route. */ stepAdvanceCondition: SerializableStepAdvanceCondition; /** * A 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. */ arrivalStepAdvanceCondition: SerializableStepAdvanceCondition; /** * Configures 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. */ routeDeviationTracking: RouteDeviationTracking; /** * Configures how the heading component of the snapped location is reported in [`TripState`]. */ snappedLocationCourseFiltering: CourseFiltering; } export class NavigationController { free(): void; [Symbol.dispose](): void; getInitialState(location: any): any; advanceToNextStep(state: any): any; updateUserLocation(location: any, state: any): any; constructor(route: any, config: any, should_record: any); } export class NavigationReplay { free(): void; [Symbol.dispose](): void; getAllEvents(): any; getInitialRoute(): any; getEventByIndex(current_index: any): any; getTotalDuration(): any; getInitialTimestamp(): any; constructor(json: any); } export class NavigationSession { free(): void; [Symbol.dispose](): void; getInitialState(location: any): any; advanceToNextStep(state: any): any; updateUserLocation(location: any, state: any): any; constructor(route: any, config: any); } export class NavigationSessionRecording { free(): void; [Symbol.dispose](): void; getEvents(): any; getRecording(): any; getInitialState(location: any): any; advanceToNextStep(state: any): any; updateUserLocation(location: any, state: any): any; constructor(route: any, config: any); } export class RouteAdapter { free(): void; [Symbol.dispose](): void; parseResponse(response: Uint8Array): any; generateRequest(user_location: any, waypoints: any): any; /** * Creates a new RouteAdapter with a Valhalla HTTP request generator and an OSRM response parser. * At the moment, this is the only supported combination. */ constructor(well_known_route_provider: WellKnownRouteProvider); } /** * JavaScript wrapper for `advance_location_simulation`. */ export function advanceLocationSimulation(state: any): any; /** * JavaScript wrapper for `location_simulation_from_coordinates`. */ export function locationSimulationFromCoordinates(coordinates: any, resample_distance: number | null | undefined, bias: LocationBias): any; /** * JavaScript wrapper for `location_simulation_from_polyline`. */ export function locationSimulationFromPolyline(polyline: string, precision: number, resample_distance: number | null | undefined, bias: LocationBias): any; /** * JavaScript wrapper for `location_simulation_from_route`. */ export function locationSimulationFromRoute(route: any, resample_distance: number | null | undefined, bias: LocationBias): any;