This is the documentation of version 1.0.0-rc.0. Go to the latest version, 1.0.0-rc.5.
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 and click 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
    • 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);

    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
      const map = myModule.mapLibreMap;
      ids.mySource.layerIDs.forEach(layerId => {
      map.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.

      // 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 selected feature
      const { click: [selectedID] = [] } = 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 | undefined;
          carTrainSections: RouteSections | undefined;
          countryCrossings: DisplayCountryCrossings;
          ferries: RouteSections;
          importantRoadStretchSections: RouteSections | undefined;
          incidents: RouteSections<DisplayTrafficSectionProps>;
          instructionArrows: DisplayInstructionArrows;
          instructionLines: DisplayInstructions;
          lowEmissionZoneSections: RouteSections | undefined;
          mainLines: Routes<DisplayRouteProps>;
          motorwaySections: RouteSections | undefined;
          pedestrianSections: RouteSections | undefined;
          speedLimitSections: RouteSections | undefined;
          summaryBubbles: DisplayRouteSummaries;
          tollRoads: RouteSections;
          tollVignetteSections: RouteSections | undefined;
          tunnels: RouteSections;
          unpavedSections: RouteSections | undefined;
          urbanSections: RouteSections | undefined;
          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
      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

      • index: number

        Zero-based index of the route to select.

      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.

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

      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. layers takes complete MapLibre layer specs. If you provide no custom layers, the module uses defaultRoutingLayers.

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