This is the documentation of version 1.0.0-rc.0. Go to the latest version, 1.0.0-rc.5.

Routing quickstart

calculateRoute plans a route through an ordered list of locations and returns a GeoJSON FeatureCollection of route features, with the best route first. It runs in the browser and in Node.js.

Initialization

import { TomTomConfig } from '@tomtom-org/maps-sdk/core';

TomTomConfig.instance.put({ apiKey: 'YOUR_API_KEY' });

The global configuration also sets the language and units every call uses.

Calculating a route

import { calculateRoute } from '@tomtom-org/maps-sdk/services';

const routes = await calculateRoute({
    locations: [
        [4.9041, 52.3676], // Amsterdam
        [2.3522, 48.8566]  // Paris
    ]
});

Accessing route information

const { summary } = routes.features[0].properties;

console.log(`Distance: ${summary.lengthInMeters} m`);
console.log(`Duration: ${summary.travelTimeInSeconds} s`);

The route object lists the summary, sections, guidance and progress fields. What the routing SDK adds lists the fields the SDK adds to the API response.

Showing a route on the map

RoutingModule.showRoutes takes the response unchanged:

import { TomTomMap, RoutingModule } from '@tomtom-org/maps-sdk/map';
import { calculateRoute } from '@tomtom-org/maps-sdk/services';

const map = new TomTomMap({ mapLibre: { container: 'map' } });
const routingModule = await RoutingModule.create(map);

const locations = [[4.9041, 52.3676], [2.3522, 48.8566]];
const routes = await calculateRoute({ locations });

await routingModule.showRoutes(routes);
await routingModule.showWaypoints(locations);

Displaying routes covers the module's selection, waypoints, events and sections.

Planning again on every change

If you recalculate the route whenever a waypoint moves or an option changes, a slow earlier plan can finish after a newer one and draw a stale route. Run each plan through createLatestRequest, as the route sections playground does:

import { calculateRoute, createLatestRequest } from '@tomtom-org/maps-sdk/services';

const latestPlan = createLatestRequest();

const showRoute = async (locations) => {
    const plan = await latestPlan.run((signal) => calculateRoute({ locations, signal }));
    if (!plan.current) return; // a newer change retired this plan

    await routingModule.showWaypoints(locations);
    await routingModule.showRoutes(plan.value);
};

API reference

Related guides and examples

Related guides

Map integration

Related examples