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

Request options and errors

Every service call takes the same options on top of its own parameters: request validation, lifecycle hooks, overrides of the global configuration, and a signal to cancel it. Each call runs them in a fixed order:

  1. An already-aborted signal rejects at once, before any work.
  2. The global configuration is merged under the call's parameters.
  3. The parameters are validated, unless validateRequest: false.
  4. The request is built, and onAPIRequest sees it.
  5. The request is sent, retrying a 429 as retry says.
  6. onAPIResponse sees the raw response, or the error, and the response is parsed.

Request validation

Before sending, the SDK checks the parameters against the service's schema, so a malformed call fails early, with a message in the SDK's terms, and never reaches the API (or your usage quota).

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

await discoverPlaces({ query: 'Eiffel Tower', validateRequest: false });

Service lifecycle hooks: onAPIRequest and onAPIResponse

Observe what a call sends and receives, for logging, debugging or analytics. Neither hook can change the request or the response.

await discoverPlaces({
    query: 'Eiffel Tower',
    onAPIRequest: (apiRequest) => console.debug('Request:', apiRequest),
    onAPIResponse: (apiRequest, apiResponse) => console.debug('Response:', apiResponse)
});

Per-call overrides

The API key, language, geopolitical view and base URL set in the global configuration can be passed to a single call instead, and win for that call only:

// French for this call only; later calls keep the global language
await discoverPlaces({ query: 'restaurants', language: 'fr-FR' });

Cancelling a request

Every call accepts a signal, an AbortSignal. Aborting it cancels the HTTP request and rejects the call with an SDKAbortError, whose name is 'AbortError'.

Keeping only the latest request

When a new request supersedes an older one (a click lookup, a search-as-you-type box, a search re-run on every map move), a slow earlier response can otherwise land after a faster later one and overwrite it.

createLatestRequest holds one such request at a time. Each run aborts the one before it and hands your callback a fresh signal; cancel aborts without starting another:

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

const latestLookup = createLatestRequest();

map.mapLibreMap.on('click', async (event) => {
    const lookup = await latestLookup.run((signal) =>
        reverseGeocode({ position: event.lngLat.toArray(), signal })
    );
    if (!lookup.current) return; // a newer click or a cancel retired it
    showAddress(lookup.value);
});

clearButton.addEventListener('click', latestLookup.cancel);

Deadlines

There is no timeout option. Compose a deadline onto the signal, alone or together with your own cancellation:

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

// A short deadline for a search box
await getSearchSuggestions({
    query: 'coffee',
    geoBias: { position: [4.9041, 52.3676] },
    signal: AbortSignal.timeout(3000)
});

// A longer one for a route, still retired by the next run
const latestRoute = createLatestRequest();
const route = await latestRoute.run((signal) =>
    calculateRoute({
        locations: [[4.9041, 52.3676], [2.3522, 48.8566]],
        signal: AbortSignal.any([signal, AbortSignal.timeout(15000)])
    })
);

Error handling

A service call rejects with an SDKError. Its code says what went wrong, service names the service that failed, and sdkVersion the SDK version, for bug reports:

code When
INVALID_REQUEST The SDK's request validation failed (issues lists why), or the API answered 400 or another 4xx not below
INSECURE_BASE_URL commonBaseURL is not https:, and not a loopback address either
API_KEY_REJECTED The API answered 401 or 403: the key is missing, invalid, expired, or not enabled for that API
NOT_FOUND The API answered 404
RATE_LIMITED The API answered 429, still after the retries
SERVICE_UNAVAILABLE The API answered a 5xx
NETWORK_ERROR No response arrived: offline, DNS, TLS or CORS failure. cause holds what fetch threw
ABORTED The signal was aborted. cause holds the abort reason
UNEXPECTED Anything else, such as a response the SDK could not read

Two subclasses carry more:

Error When Carries
SDKServiceError The API answered with an error status status
SDKAbortError The signal was aborted cause: the abort reason

discoverOnePlace and geocodeOne also throw a plain Error when nothing matches the query; use discoverPlaces or geocode to get an empty result instead.

import { discoverPlaces, SDKError } from '@tomtom-org/maps-sdk/services';

try {
    const results = await discoverPlaces({
        query: 'coffee',
        geoBias: { position: [4.9041, 52.3676] },
        signal: AbortSignal.timeout(5000)
    });
} catch (error) {
    if (!(error instanceof SDKError)) throw error;

    switch (error.code) {
        case 'ABORTED':
            console.error('Search timed out');
            break;
        case 'API_KEY_REJECTED':
            console.error('Check the API key and the APIs it is enabled for');
            break;
        case 'RATE_LIMITED':
            console.error('Rate limited, even after retrying');
            break;
        case 'NETWORK_ERROR':
            console.error('No connection');
            break;
        default:
            console.error(`${error.service} failed (${error.code}, SDK ${error.sdkVersion}): ${error.message}`);
    }
}

Related guides and examples

Related guides

Related examples