TomTom Maps for JavaScript
    Preparing search index...

    Class RoutingModule

    The map module that displays and manages routes.

    It draws route lines, alternative routes, turn-by-turn guidance and waypoints, and works with the TomTom Routing API.

    Features:

    • Display route lines with customizable styling
    • Show alternative routes with different styling
    • Waypoint pins per role (origin, numbered or lettered stops, destination), with hover, click and drag events
    • Turn-by-turn guidance instructions
    • Route section highlighting
    • Distance and duration information
    • Several routes at once

    Common use cases:

    • Turn-by-turn navigation displays
    • Route planning and comparison
    • Multi-stop route optimization
    • Interactive route editing: drag a waypoint to move its stop, or a route line to pull a new stop onto it. The module reports the drag on events.waypoints and events.mainLines and plans nothing: you call calculateRoute and showRoutes with the new waypoints.
    • Fleet management route visualization
    // Create the module
    const routingModule = await RoutingModule.create(map, {
    displayUnits: {
    distance: { type: 'metric' }
    }
    });

    // Calculate and display a route
    const result = await calculateRoute({
    apiKey: 'your-api-key',
    locations: [
    [4.9041, 52.3676], // Amsterdam
    [4.4777, 51.9244] // Rotterdam
    ],
    travelMode: 'car',
    costModel: { routeType: 'fast' }
    });

    await routingModule.showRoutes(result);

    Drag a waypoint to move its stop, then plan again:

    routingModule.events.waypoints.on('drag', async (waypoint, lngLat) => {
    waypoints[waypoint.properties.index] = lngLat.toArray();
    await routingModule.showWaypoints(waypoints);
    });
    routingModule.events.waypoints.on('dragend', async () => {
    await routingModule.showRoutes(await calculateRoute({ locations: waypoints }));
    });

    Hierarchy (View Summary)

    Index
    • get events(): RoutingEvents

      The routing module's events, in one interface.

      events itself covers every route feature and the module's lifecycle events. Each named scope below covers one part of a route, and you can narrow any of them further with where().

      routing.events.mainLines.on('click', (route) => { ... });
      routing.events.waypoints.on('hover', (waypoint) => { ... });

      // Only the selected route's tunnels, with their own hover cursor:
      routing.events.tunnels
      .where((section) => section.properties.routeState === 'selected', { cursorOnHover: 'help' })
      .on('click', showTunnel);

      const unsub = routing.events.on('config-change', (config) => { ... });
      routing.events.on('shown-features', (features) => {
      if ('routes' in features) { ... }
      });
      unsub();

      Returns RoutingEvents

    • get sourceAndLayerIDs(): Record<keyof SOURCES_WITH_LAYERS, SourceWithLayerIDs>

      The MapLibre source and layer IDs of all sources this module creates and manages.

      Returns Record<keyof SOURCES_WITH_LAYERS, SourceWithLayerIDs>

      A record mapping each source name to its MapLibre source ID and an array of the IDs of that source's layers.

      Use these IDs to:

      • Directly manipulate layers using MapLibre's native API
      • Identify which layers on the map belong to this module
      • Set layer ordering or positioning relative to other layers
      • Access source or layer properties through MapLibre methods
      const ids = myModule.sourceAndLayerIDs;
      console.log(ids);
      // {
      // mySource: {
      // sourceID: 'my-source-id',
      // layerIDs: ['layer-1', 'layer-2']
      // }
      // }

      // Use with MapLibre API
      ids.mySource.layerIDs.forEach(layerId => {
      map.mapLibreMap.setLayoutProperty(layerId, 'visibility', 'visible');
      });
    • Applies a configuration to this module.

      The module updates its behaviour and appearance to match. It stores the configuration and reapplies it automatically when the map style changes.

      Parameters

      • config: RoutingModuleConfig | undefined

        The configuration to apply. Pass undefined to reset it to the default values.

      Returns void

      The given configuration replaces the current one rather than being merged into it. To change one part of it, use updateConfig.

      Use it for settings your code writes. It takes every setting, typed, including the ones no knob covers (layer specs, callbacks, MapLibre expressions), and checks no value at run time. For settings held as data, from a control, storage or a language model, use setKnobs.

      // Apply a new configuration
      myModule.applyConfig({ visible: true, color: '#E63312' });

      // Reset to default configuration
      myModule.applyConfig(undefined);
      • resetConfig for a convenience method to reset configuration
      • getConfig to retrieve the current configuration
    • Clears any previously shown routes from the map.

      Returns Promise<void>

      • Clears all route-related layers (lines, sections, guidance, summaries)
      • Doesn't clear waypoints. For those, use clearWaypoints
      • Module remains initialized and ready for new routes
      await routing.clearRoutes();
      
    • Clears any previously shown waypoints from the map. If nothing was shown before, nothing happens.

      Returns Promise<void>

    • Returns a shallow copy of the current module configuration, or undefined if none is applied.

      Returns NonNullable<RoutingModuleConfig> | undefined

      A shallow copy of the current configuration, or undefined. It is a copy so that you can't modify the internal state by accident.

      Only the top-level properties are copied. Nested objects and arrays still reference the original configuration. This is enough for most use cases, but keep it in mind with complex configurations.

      // Apply a configuration
      myModule.applyConfig({ visible: true, color: '#E63312' });

      // Later, retrieve the current configuration
      const currentConfig = myModule.getConfig();
      console.log(currentConfig); // { visible: true, color: '#E63312' }

      // When no config is applied
      myModule.resetConfig();
      console.log(myModule.getConfig()); // undefined
    • Returns the ids of the shown features that have an event state, by state.

      Returns EventStateIds

      The read side of setEventState and clearEventStates, reflecting those and the states user interactions put. The ids are those getShown() and the event handlers hand back, so each can go straight back into setEventState.

      // Keep a list in sync with the clicked feature
      const { click: [clickedID] = [] } = module.getEventStates();

      // Is this feature hovered?
      const hovered = module.getEventStates().hover?.includes(feature.properties.id) ?? false;
    • Returns the map style layer the route lines render under, or undefined when they are on top of the stack.

      Use it to render extra layers just above the route lines but not on top of everything else. It follows beforeLayerConfig, and can differ with the loaded style or its version.

      Returns string | undefined

    • Returns the currently shown routes and waypoints.

      Returns {
          carpoolSections: RouteSections;
          carTrainSections: RouteSections;
          countryCrossings: DisplayCountryCrossings;
          curveSections: RouteSections;
          curvyStretchSections: RouteSections;
          ferries: RouteSections;
          importantRoadStretchSections: RouteSections;
          incidents: RouteSections<DisplayTrafficSectionProps>;
          instructionArrows: DisplayInstructionArrows;
          instructionLines: DisplayInstructions;
          lowEmissionZoneSections: RouteSections;
          mainLines: Routes<DisplayRouteProps>;
          motorwaySections: RouteSections;
          pedestrianSections: RouteSections;
          sectionFocus: RouteSections;
          speedLimitSections: RouteSections<DisplaySpeedLimitSectionProps>;
          summaryBubbles: DisplayRouteSummaries;
          tollRoads: RouteSections;
          tollVignetteSections: RouteSections;
          tunnels: RouteSections;
          unpavedSections: RouteSections;
          urbanSections: RouteSections;
          vehicleRestricted: RouteSections;
          waypoints: Waypoints<WaypointDisplayProps>;
      }

      An object containing all currently displayed routing data.

      Returns what each source draws, as prepared for display from what showRoutes() and showWaypoints() were given.

      Returned data:

      • mainLines: Main route lines (selected and alternative)
      • waypoints: Route waypoints (start, stops, finish)
      • incidents: Traffic incidents on routes
      • ferries: Ferry sections
      • tollRoads: Sections that cost money to drive, of the tollRoad section type
      • tunnels: Tunnel sections
      • vehicleRestricted: Vehicle-restricted sections
      • <type>Sections: Each other drawn section type, such as urbanSections
      • instructionLines: Turn-by-turn instruction lines
      • instructionArrows: Instruction arrow markers
      • summaryBubbles: Route summary popups
      • countryCrossings: Border crossings along the route
      • sectionFocus: The sections setSectionFocus() rings
      const shown = routingModule.getShown();
      console.log(`Showing ${shown.mainLines.features.length} routes`);
      console.log(`Showing ${shown.waypoints.features.length} waypoints`);

      Check if any routes are displayed:

      const shown = routingModule.getShown();
      if (shown.mainLines.features.length > 0) {
      console.log('Routes are displayed');
      } else {
      console.log('No routes displayed');
      }
    • Whether the module is set to be shown: its visible setting, true unless set. A shown module with nothing shown draws nothing. getShown() returns what is shown.

      Returns boolean

    • Resets this module's configuration to its default values.

      It clears any applied configuration and restores the module to its initial state, the same as calling applyConfig(undefined).

      Returns void

      The module then behaves as if no configuration was ever applied. Any custom settings, styling or behaviour changes are replaced with default values.

      // Apply some configuration
      myModule.applyConfig({ visible: true, color: '#E63312' });

      // Later, reset to defaults
      myModule.resetConfig();
      • applyConfig to apply a new configuration
      • getConfig to retrieve the current configuration before resetting
    • Changes which route appears as selected.

      Parameters

      • routeIndex: number

        Zero-based position of the route to select among the shown ones. A route's properties.index is its index in the routing response, which is that position only when you show every route of the response.

      Returns Promise<void>

      The selected route appears more prominent, thicker and brighter, and the previously selected one takes the deselected style. The sections, guidance and other route features update with it, and the summary bubbles' duration differences and titles are worked out again. The click event state of the route lines and summary bubbles is cleared, since the selection now marks the route.

      Show the routes with showRoutes first, and pass an index within their range.

      // Show multiple routes
      await routingModule.showRoutes(routes);

      // User clicks alternative route
      await routingModule.selectRoute(1);

      // Switch back to first route
      await routingModule.selectRoute(0);
    • Puts an event state on one of the shown features, as a user interaction would.

      Parameters

      Returns void

      The state is what the module's own layers draw (place pins and entry points, route outlines, geometries, details-module incidents, area-analytics cells), what layers of yours read with ['get', 'eventState'], and what getEventStates returns. It lasts as long as the shown feature does, through setVisible, style and configuration changes, but not a new show, a clear or a setStyle with resetState.

      // Select a feature from a list, as a click would
      module.setEventState({ id: feature.properties.id, state: 'click' });

      // Hover a second one without taking the hover off the first
      module.setEventState({ index: 2, state: 'hover', mode: 'add' });
    • Rings the given sections of the shown routes, or clears the ring with null.

      Parameters

      • sectionIds: readonly string[] | null

        The id of each section to focus, from any route shown and of any type, drawn or not. An id no shown section carries is skipped.

      Returns Promise<void>

      The ring runs on both sides of the route, clear of the widest line it draws, whether its hovered outline or a section, so the route and every section along it stay in sight. A deselected route's ring sits under the selected route. RouteHighlightConfig section styles it. Each call replaces the focus, and showRoutes clears it.

      // Point out the route's ferry crossings, say while a timeline row hovers them
      const ferries = route.properties.sections.ferry ?? [];
      await routingModule.setSectionFocus(ferries.map((section) => section.id));

      await routingModule.setSectionFocus(null);
    • Shows or hides everything the module draws.

      Parameters

      • visible: boolean

      Returns void

      Stored as visible in the configuration. Showing and clearing data never change it. A hidden module keeps its data, through style changes too, and draws it again on setVisible(true).

      Showing leaves hidden what the configuration turns off: a route section type that is off, the layers a place marker type does not use.

      module.setVisible(false);
      await module.show(data); // stays hidden
      module.setVisible(true);
    • Displays the given routes on the map.

      Parameters

      • routes: Route | Routes

        Route data from Routing API or custom routes.

      • Optionaloptions: ShowRoutesOptions

        Optional configuration for route selection and display.

        • selectedIndex

          Index of the route to display as selected (default: 0).

      Returns Promise<void>

      This method doesn't show waypoints. It draws route lines, not start, stop or destination markers. To show them, call showWaypoints separately.

      This method:

      • Replaces any previously shown routes, and clears the setSectionFocus focus
      • Shows all route-related features: lines, sections, guidance and summary bubbles
      • Selects the first route by default, which then appears more prominent

      It draws:

      • Main route lines (selected and deselected styles)
      • Traffic sections with delays
      • Ferry, tunnel, charged-road (tollRoad) and vehicle-restricted sections, speed-limit signs, and the other section types sections shows
      • Turn-by-turn instruction lines and arrows
      • Country-crossing markers and summary bubbles with distance/time/traffic info, unless turned off

      Show a route (no waypoint markers):

      await routing.showRoutes(routes);
      // Waypoint markers are NOT shown — call showWaypoints() to add them

      Show routes and waypoint markers:

      const locations = [[4.9, 52.4], [4.5, 51.9]];
      const routes = await calculateRoute({ locations });
      await routing.showRoutes(routes);
      await routing.showWaypoints(locations); // Show start/destination markers separately

      Show multiple routes with specific selection:

      await routing.showRoutes(routes, { selectedIndex: 1 });
      
    • Displays waypoint markers (start, stop, and destination pins) on the map.

      Parameters

      Returns Promise<void>

      showRoutes doesn't show waypoint markers, so call this method separately.

      Pass every location the route is calculated through, so that its pin carries its role and stop mark and the route's events reach it. Show a place the user is still choosing among as a PlacesModule marker instead, and clear it there once it joins the route. Each pin draws as RoutingModuleConfig.waypoints sets, including the per-role pins and an icon mapped from the waypoint's data.

      Show routes and then waypoints:

      const locations = [[4.9041, 52.3676], [4.4777, 51.9244]];
      const routes = await calculateRoute({ locations });
      await routingModule.showRoutes(routes);
      await routingModule.showWaypoints(locations); // Must be called separately
    • Changes part of the configuration and keeps the rest.

      The given properties are laid over the current configuration one level deep, so a nested object you pass replaces the one that was there. The result is applied with applyConfig. This works the same on every module, whatever its applyConfig does with a whole configuration.

      Parameters

      • partial: Partial<NonNullable<CFG>>

        The properties to change.

      Returns void

      Use it for settings your code writes, as applyConfig: typed, and not checked at run time. To change nested values and keep the ones beside them, or to set values held as data, use setKnobs, which reaches each by its path and checks it.

      routing.applyConfig({ displayUnits: { distance: { type: 'imperial_us' } }, color: '#0a3653' });
      routing.updateConfig({ color: '#c2185b' }); // displayUnits stays imperial

      applyConfig to apply a whole configuration

    • Waits until the map is ready, then creates an instance of the module.

      Parameters

      Returns Promise<RoutingModule>

      RoutingModule owns the sources, layers and images it adds, all suffixed per instance. So every call returns a new, independent instance, and you can stack several of them on one map.

      routingKnobCatalogue lists every plain-valued display setting, and RoutingModuleConfig.layers the MapLibre overrides for what they can't express.

      Default initialization:

      const routingModule = await RoutingModule.create(map);
      

      With custom configuration:

      const routingModule = await RoutingModule.create(map, {
      displayUnits: { distance: { type: 'imperial_us' } },
      waypoints: {
      entryPoints: 'main-when-available'
      }
      });