TomTom Maps for JavaScript
    Preparing search index...

    Class TomTomMap

    Main TomTom Map class for displaying interactive maps in web applications.

    This is the entry point for rendering TomTom maps. It wraps MapLibre GL JS and provides a simplified, enhanced API for common mapping tasks.

    Key Features:

    • Built on MapLibre GL JS for high-performance rendering
    • Seamless style switching without map reload
    • Integrated event handling system
    • Multi-language support with dynamic switching
    • Compatible with TomTom map modules (traffic, POIs, routing, etc.)

    Architecture:

    • Exposes the underlying MapLibre Map instance via mapLibreMap
    • Manages map lifecycle and style transitions
    • Coordinates with map modules for data visualization

    Basic map initialization:

    import { TomTomMap } from '@tomtom-international/maps-sdk-js/map';

    const map = new TomTomMap({
    key: 'YOUR_API_KEY',
    style: 'standardLight',
    mapLibre: {
    container: 'map',
    center: [4.9041, 52.3676],
    zoom: 10
    }
    });

    With modules and configuration:

    const map = new TomTomMap({
    key: 'YOUR_API_KEY',
    style: {
    type: 'standard',
    id: 'standardDark',
    include: ['trafficFlow', 'trafficIncidents']
    },
    language: 'en-US',
    events: {
    precisionMode: 'point-then-box',
    cursorOnHover: 'pointer'
    },
    mapLibre: {
    container: 'map',
    center: [-74.006, 40.7128],
    zoom: 12
    }
    });

    // Access MapLibre functionality directly
    map.mapLibreMap.on('load', () => {
    console.log('Map loaded');
    });
    Index

    Constructors

    • Constructs a new TomTom Map instance and attaches it to a DOM element.

      Parameters

      • mapParams: TomTomMapParams

        Combined TomTom and MapLibre parameters for map initialization. Includes API key, style, events, and MapLibre options like container, center, zoom, etc. See TomTomMapParams for all available parameters.

      Returns TomTomMap

      Initialization Process:

      1. Merges mapParams with global configuration
      2. Creates underlying MapLibre map instance
      3. Loads specified style asynchronously
      4. Sets mapReady to true when complete

      Configuration Priority:

      • Parameters passed here override global configuration
      • Allows per-map customization while sharing common settings

      Minimal initialization:

      const map = new TomTomMap({
      key: 'YOUR_API_KEY',
      mapLibre: {
      container: 'map',
      center: [0, 0],
      zoom: 2
      }
      });

      Full configuration:

      const map = new TomTomMap({
      key: 'YOUR_API_KEY',
      style: {
      type: 'standard',
      id: 'standardLight',
      include: ['trafficFlow', 'hillshade']
      },
      language: 'en-US',
      events: {
      precisionMode: 'point-then-box',
      paddingBoxPx: 10
      },
      mapLibre: {
      container: 'map',
      center: [-122.4194, 37.7749],
      zoom: 13,
      pitch: 45,
      bearing: -17.6,
      antialias: true,
      maxZoom: 18,
      minZoom: 8
      }
      });

      Will log errors if RTL text plugin fails to load (non-blocking)

    Properties

    mapLibreMap: Map$1

    The underlying MapLibre GL JS Map instance.

    When to Use:

    • Access advanced MapLibre functionality not exposed by TomTomMap
    • Add custom layers, sources, or controls
    • Listen to MapLibre-specific events
    • Integrate third-party MapLibre plugins

    Important:

    • Available immediately after TomTomMap construction
    • Direct modifications may affect SDK module behavior
    • Coordinate with SDK modules to avoid conflicts

    Add custom layer:

    map.mapLibreMap.addLayer({
    id: 'custom-layer',
    type: 'circle',
    source: 'my-data',
    paint: {
    'circle-radius': 6,
    'circle-color': '#ff0000'
    }
    });

    Listen to events:

    map.mapLibreMap.on('moveend', () => {
    console.log('Camera position:', map.mapLibreMap.getCenter());
    });
    mapReady: boolean = false

    Indicates whether the map style has been fully loaded and is ready for interaction.

    • true when the style is loaded and modules can be safely initialized
    • false during map construction or style changes
    • Check this before performing style-dependent operations
    if (map.mapReady) {
    // Safe to initialize modules
    const trafficFlowModule = await TrafficFlowModule.get(map);
    }
    styleLightDarkTheme: LightDark

    Methods

    • Registers a handler to be notified when the map style changes.

      Parameters

      Returns void

      When to Use:

      • You have custom layers or sources that need to be recreated after style changes
      • Your application needs to respond to style switches (e.g., light/dark mode transitions)
      • You need to save and restore state during style changes
      • Map modules need to reinitialize when styles change

      Handler Lifecycle:

      1. onStyleAboutToChange() - Called before the style change begins
      2. Style change occurs
      3. onStyleChanged() - Called after the new style has been fully loaded

      Multiple Handlers:

      • Multiple handlers can be registered and will all be called in registration order
      • Each handler's errors are caught independently and logged to the console
      • One failing handler won't prevent others from executing

      Important Notes:

      • Handlers are only triggered by setStyle calls, not initial map construction
      • Only called when keepState: true in setStyle options
      • Handlers persist for the lifetime of the TomTomMap instance

      Basic usage:

      map.addStyleChangeHandler({
      onStyleAboutToChange: () => {
      console.log('Style is changing...');
      },
      onStyleChanged: () => {
      console.log('Style changed successfully!');
      }
      });

      // Later trigger the handlers
      map.setStyle('standardDark');

      Preserve custom layers across style changes:

      let customLayerData = null;

      map.addStyleChangeHandler({
      onStyleAboutToChange: () => {
      // Save custom layer data before style changes
      if (map.mapLibreMap.getLayer('my-custom-layer')) {
      customLayerData = map.mapLibreMap.getSource('my-data')._data;
      map.mapLibreMap.removeLayer('my-custom-layer');
      map.mapLibreMap.removeSource('my-data');
      }
      },
      onStyleChanged: () => {
      // Restore custom layer after new style is loaded
      if (customLayerData) {
      map.mapLibreMap.addSource('my-data', {
      type: 'geojson',
      data: customLayerData
      });
      map.mapLibreMap.addLayer({
      id: 'my-custom-layer',
      type: 'circle',
      source: 'my-data',
      paint: { 'circle-radius': 6, 'circle-color': '#007cbf' }
      });
      }
      }
      });

      Async handler for external API calls:

      map.addStyleChangeHandler({
      onStyleAboutToChange: async () => {
      await saveStateToAPI(map.getStyle());
      },
      onStyleChanged: async () => {
      await loadStateFromAPI();
      }
      });

      Update UI based on style:

      map.addStyleChangeHandler({
      onStyleAboutToChange: () => {
      document.body.classList.add('style-changing');
      },
      onStyleChanged: () => {
      document.body.classList.remove('style-changing');
      const style = map.getStyle();
      if (typeof style === 'string' && style.includes('Dark')) {
      document.body.classList.add('dark-mode');
      } else {
      document.body.classList.remove('dark-mode');
      }
      }
      });
    • Retrieves the current visible map area as a GeoJSON bounding box.

      Returns BBox

      A GeoJSON BBox array in the format [west, south, east, north] representing the map's current viewport bounds.

      Return Format:

      • Array of four numbers: [minLongitude, minLatitude, maxLongitude, maxLatitude]
      • Coordinates are in WGS84 decimal degrees
      • West/East values range from -180 to 180
      • South/North values range from -90 to 90

      Get current bounds:

      const bbox = map.getBBox();
      console.log('Bounds:', bbox);
      // Output: [-122.5, 37.7, -122.3, 37.8]
      // [west, south, east, north]

      Use bounds for spatial query:

      const bbox = map.getBBox();
      const results = await searchAPI.searchInBoundingBox({
      bbox: bbox,
      query: 'restaurants'
      });

      Save and restore map view:

      // Save current view
      const savedBounds = map.getBBox();
      const savedZoom = map.mapLibreMap.getZoom();

      // Later, restore the view
      const [west, south, east, north] = savedBounds;
      map.mapLibreMap.fitBounds([[west, south], [east, north]]);
    • Retrieves the current style configuration of the map.

      Returns StyleInput | undefined

      The current StyleInput configuration, or undefined if no style is set.

      Returns the style configuration as it was set, not the fully resolved MapLibre style object. Use this to inspect or store the current style configuration for later restoration.

      Return Value:

      • String ID (e.g., 'standardLight') for simple style configurations
      • Style object with type, id, and optional include properties for detailed configurations
      • undefined if no style has been explicitly set
      const currentStyle = map.getStyle();
      console.log('Current style:', currentStyle);

      // Save style for later
      const savedStyle = map.getStyle();

      // Later, restore it
      if (savedStyle) {
      map.setStyle(savedStyle);
      }

      Conditional logic based on current style:

      const style = map.getStyle();
      if (typeof style === 'string' && style.includes('Dark')) {
      console.log('Dark mode is active');
      }
      • setStyle - For changing the map style
      • StyleInput - For available style configuration options
    • Changes the language of the map.

      • You can use this method to change the language at runtime.
      • To set the language upon initialization, you can better do it via global config or TomTomMapParams.

      Parameters

      • language:
            | "ngt"
            | "ngt-Latn"
            | "ar"
            | "bg-BG"
            | "zh-Hant"
            | "zh-Hans"
            | "cs-CZ"
            | "da-DK"
            | "nl-NL"
            | "en-AU"
            | "en-CA"
            | "en-GB"
            | "en-NZ"
            | "en-US"
            | "fi-FI"
            | "fr-FR"
            | "de-DE"
            | "el-GR"
            | "hu-HU"
            | "id-ID"
            | "it-IT"
            | "ko-KR"
            | "ko-Latn-KR"
            | "lt-LT"
            | "ms-MY"
            | "nb-NO"
            | "pl-PL"
            | "pt-BR"
            | "pt-PT"
            | "ru-RU"
            | "ru-Latn-RU"
            | "ru-Cyrl-RU"
            | "sk-SK"
            | "sl-SI"
            | "es-ES"
            | "es-MX"
            | "sv-SE"
            | "th-TH"
            | "tr-TR"

        The language to be used in map translations.

      Returns void

      Behavior:

      • Updates all localizable map labels to the specified language
      • Falls back to the default label name if the requested language is unavailable
      • Can be called before or after the map is fully loaded
      • If called before map is ready, will apply once the style loads

      Language Format:

      • Simple language codes: 'en', 'fr', 'de', 'ja', 'zh'
      • Locale-specific codes: 'en-US', 'en-GB', 'zh-CN', 'pt-BR'
      • When using locale codes (with -), only the language portion is used for labels

      Persistence:

      • Language setting persists across style changes (when keepState: true)
      • Set during initialization via TomTomMapParams.language for immediate application

      Change language at runtime:

      // Switch to French
      map.setLanguage('fr');

      Use locale-specific codes:

      // Use Simplified Chinese
      map.setLanguage('zh-CN');

      // Use Brazilian Portuguese
      map.setLanguage('pt-BR');

      Language switcher UI:

      const languageSelector = document.getElementById('lang-select');
      languageSelector.addEventListener('change', (e) => {
      map.setLanguage(e.target.value);
      });
    • Changes the map style dynamically without reloading the entire map.

      Parameters

      • style: StyleInput

        The new style to apply. Can be a string ID or a detailed style configuration.

      • options: { keepState?: boolean } = ...

        Configuration options for the style change behavior.

        • OptionalkeepState?: boolean

          Whether to preserve SDK-rendered items and configurations when changing styles. When true (default), maintains traffic layers, routes, markers, and other SDK features. When false, performs a clean style switch without preserving previous state.

      Returns void

      Behavior:

      • Temporarily sets mapReady to false during the transition
      • Triggers all registered StyleChangeHandler callbacks
      • Resets mapReady to true when the new style is fully loaded

      State Preservation (keepState: true):

      • Merges style parts from the previous style with the new one
      • Maintains SDK module layers (traffic, routes, POIs, etc.)
      • Preserves language settings

      Clean Switch (keepState: false):

      • Applies the new style without merging previous configuration
      • Removes all SDK module layers
      • Useful for complete style resets

      Simple style change:

      // Switch to dark mode
      map.setStyle('standardDark');

      Style change with detailed configuration:

      map.setStyle({
      type: 'standard',
      id: 'standardLight',
      include: ['trafficFlow', 'hillshade']
      });

      Clean style switch without state preservation:

      // Complete reset - removes all SDK layers and modules
      map.setStyle('standardDark', { keepState: false });

      With style change handlers:

      map.addStyleChangeHandler({
      onStyleAboutToChange: () => {
      console.log('Preparing for style change...');
      },
      onStyleChanged: () => {
      console.log('New style applied!');
      }
      });

      map.setStyle('standardDark');