### Install pnpm
Source: https://docs.tomtom.com/maps-sdk-js/guides/map/quickstart
Commands to install the TomTom Maps SDK using pnpm, including enabling auto-install-peers for easier setup.
```bash
# pnpm - enable auto-install-peers for easiest setup
echo "auto-install-peers=true" >> .npmrc
pnpm install @tomtom-org/maps-sdk
```
--------------------------------
### Install npm or Yarn
Source: https://docs.tomtom.com/maps-sdk-js/guides/map/quickstart
Command to install the TomTom Maps SDK using npm or Yarn, which automatically handles peer dependency installation.
```bash
# npm or Yarn - automatic peer dependency installation
npm install @tomtom-org/maps-sdk
```
--------------------------------
### Node.js Project Setup
Source: https://docs.tomtom.com/maps-sdk-js/introduction/project-setup
Configuration for a Node.js environment and an example of using the geocoding service.
```javascript
// src/config/tomtom.js
import { TomTomConfig } from '@tomtom-org/maps-sdk/core';
TomTomConfig.instance.put({
apiKey: process.env.TOMTOM_API_KEY,
language: 'en-US'
});
// src/services/geocoding.js
import { geocode } from '@tomtom-org/maps-sdk/services';
export async function geocodeAddress(query) {
return await geocode({
query
});
}
```
--------------------------------
### Routing Services Example
Source: https://docs.tomtom.com/maps-sdk-js/guides/services/quickstart
Example of calculating a route between two locations using the Routing Services.
```javascript
import { calculateRoute } from '@tomtom-org/maps-sdk/services';
const route = await calculateRoute({
locations: [
[4.9041, 52.3676], // Amsterdam
[2.3522, 48.8566] // Paris
]
});
```
--------------------------------
### Basic Setup
Source: https://docs.tomtom.com/maps-sdk-js/guides/services/places/quickstart
Imports necessary modules and initializes the TomTom SDK with an API key.
```javascript
import { TomTomConfig } from '@tomtom-org/maps-sdk/core';
import { search, geocode, reverseGeocode } from '@tomtom-org/maps-sdk/services';
TomTomConfig.instance.put({
apiKey: 'YOUR_API_KEY_HERE'
});
```
--------------------------------
### Manual installation of peer dependencies with pnpm
Source: https://docs.tomtom.com/maps-sdk-js/introduction/project-setup
Manually installs the SDK and its required peer dependencies using pnpm.
```bash
# Install the SDK
pnpm install @tomtom-org/maps-sdk
# Manually install required peer dependencies
pnpm install lodash-es zod maplibre-gl
```
--------------------------------
### Complete Configuration Example
Source: https://docs.tomtom.com/maps-sdk-js/introduction/project-setup
Provides a comprehensive example of setting various configuration properties, including API key, language, API version, base URL, tracking ID, and display units.
```typescript
TomTomConfig.instance.put({
apiKey: process.env.TOMTOM_API_KEY,
language: 'en-GB',
apiVersion: 1,
commonBaseURL: 'https://api.tomtom.com',
trackingId: '9ac68072-c7a4-11e8-a8d5-f2801f1b9fd1', // Optional: for support tracing
displayUnits: {
distance: {
type: 'metric',
kilometers: 'km',
meters: 'm'
},
time: {
hours: 'h',
minutes: 'min'
}
}
});
```
--------------------------------
### Installing Dependencies
Source: https://docs.tomtom.com/maps-sdk-js/guides/core/quickstart
Install the Maps SDK for JavaScript using npm or Yarn. The Core bundle is automatically included when installing the Map or Services bundles.
```bash
# npm or Yarn - automatic peer dependency installation
npm install @tomtom-org/maps-sdk
# pnpm - enable auto-install-peers for easiest setup
echo "auto-install-peers=true" >> .npmrc
pnpm install @tomtom-org/maps-sdk
```
--------------------------------
### Setup API Key
Source: https://docs.tomtom.com/maps-sdk-js/guides/services/quickstart
Configure the TomTomConfig instance with your API key for using the services.
```javascript
import { TomTomConfig } from '@tomtom-org/maps-sdk/core';
TomTomConfig.instance.put({
apiKey: 'YOUR_API_KEY_HERE'
});
```
--------------------------------
### get Example
Source: https://docs.tomtom.com/maps-sdk-js/api-reference/classes/map.TrafficAreaAnalyticsModule.html
Examples demonstrating how to create and initialize a Traffic Area Analytics module.
```javascript
// No config needed — defaults are applied automatically.
const module = await TrafficAreaAnalyticsModule.get(map);
await module.show(analytics);
// Or override specific properties while keeping everything else at default:
const module = await TrafficAreaAnalyticsModule.get(map, {
displayMode: 'heatmap',
metricConfig: {
congestionLevel: { color: 'heat' },
},
});
```
--------------------------------
### Creating Your First Map
Source: https://docs.tomtom.com/maps-sdk-js/guides/map/quickstart
A complete example demonstrating essential concepts for creating a TomTom map with various configuration options.
```typescript
import { TomTomConfig } from '@tomtom-org/maps-sdk/core';
import { TomTomMap } from '@tomtom-org/maps-sdk/map';
// Configure global SDK settings
TomTomConfig.instance.put({
apiKey: 'YOUR_API_KEY_HERE',
});
const map = new TomTomMap({
mapLibre: {
container: 'map'
}
});
```
--------------------------------
### Geocode an Address
Source: https://docs.tomtom.com/maps-sdk-js/guides/services/places/quickstart
Example of geocoding an address to retrieve its coordinates.
```javascript
const result = await geocode({
query: 'Dam Square, Amsterdam'
});
const coordinates = result.features[0].geometry.coordinates; // [lng, lat]
```
--------------------------------
### Example: get (Start hidden)
Source: https://docs.tomtom.com/maps-sdk-js/api-reference/classes/map.HillshadeModule.html
Illustrates initializing HillshadeModule to start in a hidden state.
```javascript
const hillshadeModule = await HillshadeModule.get(map, {
visible: false
});
```
--------------------------------
### Install SDK with npm or Yarn (automatic peer dependency installation)
Source: https://docs.tomtom.com/maps-sdk-js/introduction/project-setup
Installs the TomTom Maps SDK using npm or Yarn, which automatically handle peer dependencies.
```bash
npm install @tomtom-org/maps-sdk
# or
yarn add @tomtom-org/maps-sdk
```
--------------------------------
### Places Services Examples
Source: https://docs.tomtom.com/maps-sdk-js/guides/services/quickstart
Demonstrates how to use search, geocode, and reverseGeocode functions from the Places Services.
```javascript
import { search, geocode, reverseGeocode } from '@tomtom-org/maps-sdk/services';
// Search for places
const results = await search({
query: 'restaurants',
position: [4.9041, 52.3676]
});
// Geocode address
const location = await geocode({
query: 'Dam Square, Amsterdam'
});
// Reverse geocode coordinates
const address = await reverseGeocode({
position: [4.9041, 52.3676]
});
```
--------------------------------
### TypeScript Support Example
Source: https://docs.tomtom.com/maps-sdk-js/introduction/project-setup
Demonstrates how to import types from the TomTom Maps SDK for TypeScript projects.
```typescript
import { TomTomConfig, type Language } from '@tomtom-org/maps-sdk/core';
import { TomTomMap } from '@tomtom-org/maps-sdk/map';
// Full TypeScript support included
```
--------------------------------
### Node.js Usage Example
Source: https://docs.tomtom.com/maps-sdk-js/guides/services/quickstart
Demonstrates using the Maps SDK Services in a Node.js environment, including setting the API key from environment variables.
```javascript
const { TomTomConfig } = require('@tomtom-org/maps-sdk/core');
const { search, calculateRoute } = require('@tomtom-org/maps-sdk/services');
TomTomConfig.instance.put({
apiKey: process.env.TOMTOM_API_KEY
});
const results = await search({
query: 'coffee shops',
position: [4.9041, 52.3676]
});
```
--------------------------------
### Configure pnpm for automatic peer dependency installation
Source: https://docs.tomtom.com/maps-sdk-js/introduction/project-setup
Configures pnpm to automatically install peer dependencies.
```bash
# Enable automatic peer dependency installation (one-time setup)
echo "auto-install-peers=true" >> .npmrc
# Now install the SDK - peer dependencies install automatically
pnpm install @tomtom-org/maps-sdk
```
--------------------------------
### get Example - Default initialization
Source: https://docs.tomtom.com/maps-sdk-js/api-reference/classes/map.POIsModule.html
Example of retrieving a POIsModule instance with default initialization.
```javascript
const poisModule = await POIsModule.get(map);
```
--------------------------------
### Basic HTML Setup
Source: https://docs.tomtom.com/maps-sdk-js/guides/map/quickstart
A basic HTML structure for a map application, including a div element for the map and a script tag to load the TypeScript file.
```html
TomTom Map Application
```
--------------------------------
### Check npm version
Source: https://docs.tomtom.com/maps-sdk-js/introduction/project-setup
Checks the currently installed npm version.
```bash
# Check your npm version
npm --version
```
--------------------------------
### get Example - With initial filter
Source: https://docs.tomtom.com/maps-sdk-js/api-reference/classes/map.POIsModule.html
Example of retrieving a POIsModule instance with an initial filter for categories.
```javascript
const poisModule = await POIsModule.get(map, {
visible: true,
filters: {
categories: {
show: 'only',
values: ['RESTAURANT', 'CAFE_PUB']
}
}
});
```
--------------------------------
### Example: get (Default initialization)
Source: https://docs.tomtom.com/maps-sdk-js/api-reference/classes/map.HillshadeModule.html
Shows the default way to retrieve a HillshadeModule instance for a map.
```javascript
const hillshadeModule = await HillshadeModule.get(map);
```
--------------------------------
### Reverse Geocode Coordinates
Source: https://docs.tomtom.com/maps-sdk-js/guides/services/places/quickstart
Example of reverse geocoding to find the address associated with a given set of coordinates.
```javascript
const result = await reverseGeocode({
position: [4.9041, 52.3676]
});
console.log(result.features[0].properties.address.freeformAddress);
```
--------------------------------
### Search for Places
Source: https://docs.tomtom.com/maps-sdk-js/guides/services/places/quickstart
Example of searching for places, specifically 'coffee shops', near a given position in Amsterdam.
```javascript
const results = await search({
query: 'coffee shops',
position: [4.9041, 52.3676] // Amsterdam
});
console.log(results.features[0].poi.name);
```
--------------------------------
### Example: get (Auto-add to style if missing)
Source: https://docs.tomtom.com/maps-sdk-js/api-reference/classes/map.HillshadeModule.html
Demonstrates initializing HillshadeModule and ensuring it's added to the map style if missing.
```javascript
const hillshadeModule = await HillshadeModule.get(map, {
visible: true
});
```
--------------------------------
### React Project Setup
Source: https://docs.tomtom.com/maps-sdk-js/introduction/project-setup
Configuration and basic map component setup for a React project using the TomTom Maps SDK.
```javascript
// src/config/tomtom.js
import { TomTomConfig } from '@tomtom-org/maps-sdk/core';
TomTomConfig.instance.put({
apiKey: process.env.REACT_APP_TOMTOM_API_KEY,
language: 'en-US'
});
// src/components/Map.jsx
import { TomTomMap } from '@tomtom-org/maps-sdk/map';
import { useEffect, useRef } from 'react';
export function MapComponent() {
const mapRef = useRef();
useEffect(() => {
const map = new TomTomMap({
mapLibre: {
container: mapRef.current
}
});
return () => map.remove();
}, []);
return ;
}
```
--------------------------------
### Runtime Configuration Updates
Source: https://docs.tomtom.com/maps-sdk-js/introduction/project-setup
Illustrates how to update specific configuration properties at runtime using the put() method, retrieve the current configuration with get(), and reset to defaults.
```typescript
// Update specific configuration properties
TomTomConfig.instance.put({ language: 'fr-FR' });
// Get current configuration
const currentConfig = TomTomConfig.instance.get();
console.log('Current language:', currentConfig.language);
// Reset to defaults (Note: default apiKey is empty string)
TomTomConfig.instance.reset();
```
--------------------------------
### Vue Project Setup
Source: https://docs.tomtom.com/maps-sdk-js/introduction/project-setup
Configuration and basic map component setup for a Vue.js project using the TomTom Maps SDK.
```javascript
// src/plugins/tomtom.js
import { TomTomConfig } from '@tomtom-org/maps-sdk/core';
TomTomConfig.instance.put({
apiKey: process.env.VUE_APP_TOMTOM_API_KEY,
language: 'en-US'
});
// src/components/MapComponent.vue
```
--------------------------------
### Example Start Date (String)
Source: https://docs.tomtom.com/maps-sdk-js/api-reference/types/services.TrafficAreaAnalyticsDateRange.html
An example of how to specify the startDate property as an ISO 'YYYY-MM-DD' string.
```javascript
'2024-08-01'
```
--------------------------------
### index.ts
Source: https://docs.tomtom.com/maps-sdk-js/guides/map/quickstart
This code snippet demonstrates how to import necessary modules, configure the TomTom SDK with an API key and language, and initialize a new TomTom map.
```typescript
import { TomTomConfig } from '@tomtom-org/maps-sdk/core';
import { TomTomMap } from '@tomtom-org/maps-sdk/map';
import './style.css';
import { API_KEY } from './config';
// (Set your own API key when working in your own environment)
TomTomConfig.instance.put({ apiKey: API_KEY, language: 'en-GB' });
new TomTomMap({
mapLibre: {
container: 'sdk-map',
center: [4.8156, 52.4414],
zoom: 8,
},
});
```
--------------------------------
### Example Start Date (Date Object)
Source: https://docs.tomtom.com/maps-sdk-js/api-reference/types/services.TrafficAreaAnalyticsDateRange.html
An example of how to specify the startDate property using a JavaScript Date object.
```javascript
new Date('2024-08-01')
```
--------------------------------
### Traffic Area Analytics Example
Source: https://docs.tomtom.com/maps-sdk-js/api-reference/types/core.TrafficAreaAnalytics.html
Example of how to use the trafficAreaAnalytics function to get traffic analysis for a polygon region.
```javascript
const result = await trafficAreaAnalytics({
startDate: new Date('2024-08-06'),
endDate: new Date('2024-08-06'),
frcs: [0, 1, 2, 3],
hours: [7, 8, 9],
metrics: ['speed', 'congestionLevel'],
feature: {
type: 'Feature',
geometry: {
type: 'Polygon',
coordinates: [[[4.89, 52.37], [4.91, 52.37], [4.91, 52.39], [4.89, 52.39], [4.89, 52.37]]]
},
properties: {}
}
});
console.log(result.properties.startDate); // Date object: 2024-08-06T00:00:00.000Z
result.features[0].properties.baseData.speed; // avg speed in km/h
result.properties.ranges.congestionLevel; // { min: 3, max: 42 } — data-driven range across all tiles
```
--------------------------------
### Quick start
Source: https://docs.tomtom.com/maps-sdk-js/api-reference/classes/map.TrafficAreaAnalyticsModule.html
Demonstrates how to initialize and use the TrafficAreaAnalyticsModule.
```javascript
import { TrafficAreaAnalyticsModule } from '@tomtom-org/maps-sdk/map';
import { trafficAreaAnalytics } from '@tomtom-org/maps-sdk/services';
const module = await TrafficAreaAnalyticsModule.get(map, {
displayMode: 'hexgrid-3d',
metric: { active: 'congestionLevel' },
});
const analytics = await trafficAreaAnalytics({ ... });
await module.show(analytics);
```
--------------------------------
### Example
Source: https://docs.tomtom.com/maps-sdk-js/api-reference/types/map.SourceWithLayerIDs.html
Get the source object using its ID.
```javascript
const source = map.getSource(sourceID);
```
--------------------------------
### Using with Map Bundle
Source: https://docs.tomtom.com/maps-sdk-js/guides/core/quickstart
Integrate the Core bundle with the Map bundle to initialize a map.
```javascript
import { TomTomConfig } from '@tomtom-org/maps-sdk/core';
import { TomTomMap } from '@tomtom-org/maps-sdk/map';
TomTomConfig.instance.put({
apiKey: 'YOUR_API_KEY_HERE'
});
const map = new TomTomMap({ mapLibre: { container: 'map' } });
```
--------------------------------
### Using with Services Bundle
Source: https://docs.tomtom.com/maps-sdk-js/guides/core/quickstart
Integrate the Core bundle with the Services bundle to perform searches.
```javascript
import { TomTomConfig } from '@tomtom-org/maps-sdk/core';
import { search } from '@tomtom-org/maps-sdk/services';
TomTomConfig.instance.put({
apiKey: 'YOUR_API_KEY_HERE'
});
const results = await search({
query: 'restaurants',
position: [4.9041, 52.3676]
});
```
--------------------------------
### TrafficIncidentDetailsByIdsParams Example
Source: https://docs.tomtom.com/maps-sdk-js/api-reference/types/services.TrafficIncidentDetailsByIdsParams.html
Demonstrates how to use the TrafficIncidentDetailsByIdsParams type to fetch traffic incidents by their IDs. It shows examples for both GET (up to 5 IDs) and POST (more than 5 IDs) requests.
```typescript
// Up to 5 IDs — sent as GET
const params: TrafficIncidentDetailsByIdsParams = {
ids: ['incident-id-1', 'incident-id-2']
};
// More than 5 IDs — sent as POST automatically
const params: TrafficIncidentDetailsByIdsParams = {
ids: manyIds
};
```
--------------------------------
### Example
Source: https://docs.tomtom.com/maps-sdk-js/api-reference/classes/map.HillshadeModule.html
Shows how to apply a new configuration and reset to default values.
```javascript
// Apply a new configuration
myModule.applyConfig({ visible: true, opacity: 0.8 });
// Reset to default configuration
myModule.applyConfig(undefined);
```
--------------------------------
### Example Usage
Source: https://docs.tomtom.com/maps-sdk-js/api-reference/functions/map.reachableRangeGeometryConfig.html
Demonstrates how to get the GeometriesModule and show reachable ranges with automatic label and theme application.
```javascript
const module = await GeometriesModule.get(map, reachableRangeGeometryConfig());
const result = await calculateReachableRanges([...]);
module.show(result); // labels and theme applied automatically
```
--------------------------------
### Showing a Route on the Map
Source: https://docs.tomtom.com/maps-sdk-js/guides/services/routing/quickstart
Demonstrates how to display a calculated route on a TomTom map using the `RoutingModule`.
```javascript
import { TomTomMap, RoutingModule } from '@tomtom-org/maps-sdk/map';
// Initialize map
const map = new TomTomMap({ mapLibre: { container: 'map' } });
// Initialize Routing Module
const routingModule = await RoutingModule.get(map);
// Calculate route
const route = await calculateRoute({
locations: [[4.9041, 52.3676], [2.3522, 48.8566]]
});
// Display on map
await routingModule.showRoutes(route);
```
--------------------------------
### Get Configuration Example
Source: https://docs.tomtom.com/maps-sdk-js/api-reference/classes/core.TomTomConfig.html
Retrieves the current global configuration object.
```javascript
const config = TomTomConfig.instance.get();
console.log(config.apiKey);
```
--------------------------------
### Install the SDK
Source: https://docs.tomtom.com/maps-sdk-js/introduction/overview
Command to install the Maps SDK for JavaScript using npm.
```bash
npm install @tomtom-org/maps-sdk
```
--------------------------------
### Example Usage
Source: https://docs.tomtom.com/maps-sdk-js/api-reference/types/services.ComputeTravelTimeFor.html
Get all traffic-based time estimates.
```javascript
// Get all traffic-based time estimates
const computeTravelTimeFor: ComputeTravelTimeFor = 'all';
```
--------------------------------
### Set up centralized configuration (After)
Source: https://docs.tomtom.com/maps-sdk-js/guides/migration/v6-to-new-sdk
Example of setting the API key once at application startup using the new SDK's singleton configuration pattern.
```javascript
import { TomTomConfig } from '@tomtom-org/maps-sdk/core';
// Set once at app startup — used by all maps and service calls
TomTomConfig.instance.put({
apiKey: 'YOUR_KEY',
language: 'en-GB',
});
```
--------------------------------
### Node.js Configuration
Source: https://docs.tomtom.com/maps-sdk-js/guides/core/quickstart
Configure the Core bundle for use in a Node.js environment, using environment variables for the API key.
```javascript
const { TomTomConfig } = require('@tomtom-org/maps-sdk/core');
TomTomConfig.instance.put({
apiKey: process.env.TOMTOM_API_KEY,
language: 'en-GB'
});
```
--------------------------------
### Get GeometriesModule Instance (Default)
Source: https://docs.tomtom.com/maps-sdk-js/api-reference/classes/map.GeometriesModule.html
Example of initializing the GeometriesModule with default settings.
```javascript
const geometriesModule = await GeometriesModule.get(map);
```
--------------------------------
### SDK Initialization
Source: https://docs.tomtom.com/maps-sdk-js/guides/services/routing/quickstart
Configure the TomTom Maps SDK for JavaScript with your API key.
```javascript
import { TomTomConfig } from '@tomtom-org/maps-sdk/core';
import { calculateRoute } from '@tomtom-org/maps-sdk/services';
TomTomConfig.instance.put({
apiKey: 'YOUR_API_KEY_HERE'
});
```
--------------------------------
### Common Configuration
Source: https://docs.tomtom.com/maps-sdk-js/guides/core/quickstart
Configure the Maps SDK with your API key and desired language.
```javascript
import { TomTomConfig } from '@tomtom-org/maps-sdk/core';
TomTomConfig.instance.put({
apiKey: 'YOUR_API_KEY_HERE',
language: 'en-GB'
});
```
```javascript
TomTomConfig.instance.put({
apiKey: 'YOUR_API_KEY_HERE',
language: 'en-GB', // Map labels language
baseUrl: 'https://api.tomtom.com', // API base URL
timeout: 10000, // Request timeout (ms)
validateRequest: true // Enable request validation
});
```
--------------------------------
### Update npm
Source: https://docs.tomtom.com/maps-sdk-js/introduction/project-setup
Updates npm to the latest version.
```bash
# Update npm if needed
npm install -g npm@latest
```
--------------------------------
### Example
Source: https://docs.tomtom.com/maps-sdk-js/api-reference/functions/services.reverseGeocode.html
Demonstrates how to use the reverseGeocode function to get an address for given coordinates, with specific street number, and nearest cross street.
```javascript
// Get address for coordinates
const address = await reverseGeocode({
key: 'your-api-key',
position: [4.9041, 52.3676] // Amsterdam coordinates
});
// Returns: Dam, 1012 Amsterdam, Netherlands
// Get address with specific street number
const specificAddress = await reverseGeocode({
key: 'your-api-key',
position: [-77.0369, 38.8977], // Washington DC
number: '1600'
});
// Returns: 1600 Pennsylvania Avenue NW
// Get nearest cross street
const crossStreet = await reverseGeocode({
key: 'your-api-key',
position: [-74.0060, 40.7128], // New York
returnRoadUse: true
});
```
--------------------------------
### Set up centralized configuration (Before V6)
Source: https://docs.tomtom.com/maps-sdk-js/guides/migration/v6-to-new-sdk
Example of how API keys were passed to every call individually in V6.
```javascript
// API key passed to every call individually
var map = tt.map({ key: 'YOUR_KEY', container: 'map' });
tt.services.fuzzySearch({ key: 'YOUR_KEY', query: 'pizza' });
```
--------------------------------
### Get Current Bounds
Source: https://docs.tomtom.com/maps-sdk-js/api-reference/classes/map.TomTomMap.html
Example of retrieving the current visible map area as a GeoJSON bounding box.
```javascript
const bbox = map.getBBox();
console.log('Bounds:', bbox);
// Output: [-122.5, 37.7, -122.3, 37.8]
// [west, south, east, north]
```
--------------------------------
### Example of setting up and handling POI events
Source: https://docs.tomtom.com/maps-sdk-js/guides/map/pois
This code demonstrates how to initialize the map, load POIs, and handle click events to display detailed information in a popup.
```typescript
import { TomTomConfig } from '@tomtom-org/maps-sdk/core';
import { BaseMapModule, PlacesModule, POIsModule, TomTomMap } from '@tomtom-org/maps-sdk/map';
import { placeById } from '@tomtom-org/maps-sdk/services';
import type { Popup } from 'maplibre-gl';
import './style.css';
import { API_KEY } from './config';
import { buildPopupHtml, createPOIPopup } from './popup';
// (Set your own API key when working in your own environment)
TomTomConfig.instance.put({ apiKey: API_KEY, language: 'en-US' });
(async () => {
const map = new TomTomMap({
mapLibre: {
container: 'sdk-map',
center: [4.90435, 52.36876],
zoom: 16,
},
});
const restOfTheMapModule = await BaseMapModule.get(map, { events: { cursorOnHover: 'default' } });
const poisModule = await POIsModule.get(map);
const placesModule = await PlacesModule.get(map);
let activePopup: Popup | null = null;
const clearSelection = async () => {
await placesModule.clear();
activePopup?.remove();
activePopup = null;
};
poisModule.events.on('click', async (feature) => {
const details = await placeById({
entityId: feature.properties.id,
openingHours: 'nextSevenDays',
});
if (!details) return;
await placesModule.show(details);
activePopup?.remove();
const [lng, lat] = details.geometry.coordinates;
activePopup = createPOIPopup().setLngLat([lng, lat]).setHTML(buildPopupHtml(details)).addTo(map.mapLibreMap);
});
restOfTheMapModule.events.on('click', async () => {
await clearSelection();
});
})();
```
--------------------------------
### Basic Geocoding Example
Source: https://docs.tomtom.com/maps-sdk-js/guides/services/places/geocoding
An example demonstrating how to initialize the SDK configuration and perform a basic geocoding query.
```javascript
import { TomTomConfig } from '@tomtom-org/maps-sdk/core';
import { geocode } from '@tomtom-org/maps-sdk/services';
import { API_KEY } from './config';
TomTomConfig.instance.put({ apiKey: API_KEY });
(async () => {
const result = await geocode({ query: 'Rue Pepin', limit: 3 });
console.log(JSON.stringify(result, null, 4));
})();
```
--------------------------------
### Global Configuration Example
Source: https://docs.tomtom.com/maps-sdk-js/api-reference/classes/core.TomTomConfig.html
Demonstrates how to set, get, and reset global configuration using the TomTomConfig singleton instance.
```javascript
TomTomConfig.instance.put({
apiKey: 'your-api-key',
language: 'en-US'
});
const config = TomTomConfig.instance.get();
TomTomConfig.instance.reset();
```
--------------------------------
### Example
Source: https://docs.tomtom.com/maps-sdk-js/api-reference/types/map.SourceWithLayerIDs.html
Get source and layer IDs from a module and update layer paint properties or remove layers and source.
```javascript
// Get source and layer IDs from a module
const { sourceID, layerIDs } = routeModule.getSourceWithLayerIDs();
// Update layer paint properties
for (const layerID of layerIDs) {
map.setPaintProperty(layerID, 'line-opacity', 0.5);
}
// Remove all layers and source
layerIDs.forEach(id => map.removeLayer(id));
map.removeSource(sourceID);
```
--------------------------------
### Example Usage
Source: https://docs.tomtom.com/maps-sdk-js/api-reference/types/core.GetPositionEntryPointOption.html
Demonstrates how to use the GetPositionEntryPointOption to specify entry point handling when getting a position from a place.
```javascript
// Get position preferring entry point for routing
const position = getPosition(place, { useEntryPoint: 'main-when-available' });
// Get center position ignoring entry points
const centerPos = getPosition(place, { useEntryPoint: 'ignore' });
```
--------------------------------
### Putting it all together: Mixing tool patterns
Source: https://docs.tomtom.com/maps-sdk-js/guides/plugins/agent-toolkit/customizing-tools
An example showing a comprehensive agent configuration that mixes custom tools, backend-backed tools, and selective disabling of default tools, along with data entry configuration.
```javascript
const agent = createMapAgent(map, {
model: openai('gpt-4o'),
// Narrow the data surface — drops every byod-related default tool.
dataEntries: {
byod: { enabled: false },
routes: { entryMode: 'single' },
},
// Per-key overrides on top of what dataEntries left.
tools: {
// Remove what doesn't fit the deployment
setLanguage: false,
executeMaplibreCode: false,
// Replace with a backend-backed version
getCurrentLocation: fleetCurrentLocationTool,
// Add new domain tools
getFleetVehicle,
getDispatchJobs,
},
});
```
--------------------------------
### Geocode a query and get the best matching place
Source: https://docs.tomtom.com/maps-sdk-js/api-reference/functions/services.geocodeOne.html
Example of using geocodeOne to find the coordinates of a place.
```javascript
const place = await geocodeOne('Amsterdam Centraal');
console.log(place.geometry.coordinates); // [lng, lat]
```
--------------------------------
### Migrate map initialization (Before V6)
Source: https://docs.tomtom.com/maps-sdk-js/guides/migration/v6-to-new-sdk
Example of map initialization in V6.
```javascript
var map = tt.map({
key: 'YOUR_KEY',
container: 'map',
center: [4.8156, 52.4414],
zoom: 8,
});
```
--------------------------------
### Get GeometriesModule Instance (Custom Styling)
Source: https://docs.tomtom.com/maps-sdk-js/api-reference/classes/map.GeometriesModule.html
Example of initializing the GeometriesModule with custom color, line, text, and layer configurations.
```javascript
const geometriesModule = await GeometriesModule.get(map, {
colorConfig: {
fillColor: 'blue',
fillOpacity: 0.25
},
lineConfig: {
lineColor: 'darkblue',
lineWidth: 2,
lineOpacity: 0.8
},
textConfig: {
textField: ['get', 'title']
},
beforeLayerConfig: 'top'
});
```
--------------------------------
### Multiple API Keys Configuration
Source: https://docs.tomtom.com/maps-sdk-js/introduction/project-setup
Demonstrates how to configure multiple API keys for different services or components within an application.
```javascript
// Global configuration with default key
TomTomConfig.instance.put({
apiKey: process.env.TOMTOM_DEFAULT_API_KEY,
language: 'en-US'
});
// Service-specific key override
import { search } from '@tomtom-org/maps-sdk/services';
const results = await search({
query: 'restaurants',
position: [4.9041, 52.3676],
apiKey: process.env.TOMTOM_PREMIUM_API_KEY // Override for this call
});
// Map-specific key override
import { TomTomMap } from '@tomtom-org/maps-sdk/map';
const map = new TomTomMap({
mapLibre: {
container: 'map'
},
apiKey: process.env.TOMTOM_MAP_API_KEY // Override for this map
});
```
--------------------------------
### Basic Usage Example
Source: https://docs.tomtom.com/maps-sdk-js/guides/services/traffic/traffic-area-analytics
Demonstrates how to call the trafficAreaAnalytics function with various parameters to get traffic data for a specified region.
```javascript
import { TomTomConfig } from '@tomtom-org/maps-sdk/core';
import { trafficAreaAnalytics } from '@tomtom-org/maps-sdk/services';
TomTomConfig.instance.put({ apiKey: 'your-api-key' });
const result = await trafficAreaAnalytics({
startDate: '2024-08-06', // YYYY-MM-DD string or Date object
endDate: '2024-08-06', // optional — defaults to today when omitted
metrics: ['speed', 'congestionLevel'], // or 'all' to include every metric
functionalRoadClasses: ['MOTORWAY', 'MAJOR_ROAD', 'OTHER_MAJOR_ROAD', 'SECONDARY_ROAD', 'LOCAL_CONNECTING_ROAD', 'LOCAL_ROAD_HIGH_IMPORTANCE'],
hours: [7, 8, 9, 17, 18], // morning and evening rush hours
geometry: {
type: 'Polygon',
coordinates: [
[[4.896128, 52.382402], [4.875701, 52.368459], [4.923611, 52.36341], [4.896128, 52.382402]]
]
}
});
const region = result.features[0];
console.log(region.properties.baseData.speed); // avg speed (km/h)
console.log(region.properties.baseData.congestionLevel); // congestion %
```
--------------------------------
### Explicit control example
Source: https://docs.tomtom.com/maps-sdk-js/api-reference/functions/map.prepareReachableRangesForDisplay.html
Shows how to use `prepareReachableRangesForDisplay` with explicit control over labels or theme.
```javascript
module.show(prepareReachableRangesForDisplay(result, 'inverted'));
module.show(prepareReachableRangesForDisplay(result, 'filled', (f) => myLabel(f)));
```