TomTom Maps for JavaScript
    Preparing search index...

    Class GeometriesModule

    The module that displays polygon areas with custom styling on the map.

    It visualizes geographic areas (polygons) with customizable colours, borders, and labels. Use it to display search results, administrative boundaries, service areas, or any polygon-based geographic data.

    Features:

    • Display single or multiple polygon geometries
    • Customizable fill colors and opacity
    • Configurable borders (color, width, opacity)
    • Optional text labels for geometries
    • Support for data-driven styling via MapLibre expressions
    • Layer ordering control
    • Event handling for user interactions

    Data format:

    • Accepts GeoJSON Polygon and MultiPolygon features
    • Supports FeatureCollection for multiple geometries
    • Compatible with TomTom Search API geometry results
    • Reachable ranges have a module of their own, ReachableRangesModule

    Styling:

    • One colour, a palette of your own, or the map's accent by default
    • Apply MapLibre expressions for dynamic styling
    • Per-feature styling via feature properties

    Basic usage:

    import { GeometriesModule } from '@tomtom-org/maps-sdk/map';

    // Initialize module
    const geometriesModule = await GeometriesModule.create(map);

    // Display a polygon
    await geometriesModule.show({
    type: 'FeatureCollection',
    features: [
    {
    type: 'Feature',
    bbox: [4.88, 52.37, 4.89, 52.38],
    geometry: {
    type: 'Polygon',
    coordinates: [[[4.88, 52.37], [4.89, 52.37], [4.89, 52.38], [4.88, 52.38], [4.88, 52.37]]]
    },
    properties: {
    title: 'Area of Interest'
    }
    }
    ]
    });

    Custom styling:

    const geometriesModule = await GeometriesModule.create(map, {
    fill: { color: '#FF5733', opacity: 0.3 },
    line: { color: '#C70039', width: 3 },
    label: {
    title: ['get', 'name']
    }
    });

    await geometriesModule.show(polygonFeatures);

    Multiple geometries with different colors:

    await geometriesModule.show({
    type: 'FeatureCollection',
    features: [
    {
    type: 'Feature',
    geometry: { type: 'Polygon', coordinates: [...] },
    properties: { color: '#FF0000', title: 'Red Zone' }
    },
    {
    type: 'Feature',
    geometry: { type: 'Polygon', coordinates: [...] },
    properties: { color: '#00FF00', title: 'Green Zone' }
    }
    ]
    });

    Event handling:

    geometriesModule.events.on('click', (feature, lngLat) => {
    console.log('Clicked geometry:', feature.properties.title);
    console.log('At coordinates:', lngLat);
    });

    geometriesModule.events.on('hover', (feature) => {
    showTooltip(feature.properties.title);
    });

    Hierarchy (View Summary)

    Index
    • get defaultColor(): string

      The map's colour for what carries no color under a config without a top-level color. It is the accent when a theme has set one, otherwise a colour that follows the active light/dark theme.

      Returns string

    • get events(): GeometriesEvents<CFG>

      The events interface for handling user interactions with the polygons.

      Returns GeometriesEvents<CFG>

      The module's events, with on and off for handlers and where for scoping.

      Supported events:

      • click: User clicks on a polygon
      • contextmenu: User right-clicks on a polygon
      • hover: Mouse enters a polygon
      • long-hover: Mouse hovers over a polygon for extended time
      module.events.on('click', (feature, lngLat) => {
      console.log('Clicked:', feature.properties);
      console.log('Location:', lngLat);
      });

      // Only the polygons, not their labels
      module.events.geometry.on('hover', (feature) => showTooltip(feature.properties.title));
    • get lightDark(): LightDark

      Current light/dark map theme, re-read on every layer/data build so style switches repaint.

      Returns LightDark

    • 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
      ids.mySource.layerIDs.forEach(layerId => {
      map.mapLibreMap.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: GeometriesModuleConfig | 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.

      Use it for settings your code writes. It takes every setting, typed, including the ones no knob covers (layer specs, callbacks, MapLibre expressions), and checks no value at run time. For settings held as data, from a control, storage or a language model, use setKnobs.

      // 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
    • Removes everything the module shows.

      Returns Promise<void>

      It clears the polygons and their labels but keeps the styling configuration. The module stays ready for new data.

      await module.clear();
      await module.show(newData);
    • Returns a shallow copy of the current module configuration, or undefined if none is applied.

      Returns NonNullable<GeometriesModuleConfig> | 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 clicked feature
      const { click: [clickedID] = [] } = module.getEventStates();

      // Is this feature hovered?
      const hovered = module.getEventStates().hover?.includes(feature.properties.id) ?? false;
    • 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
    • 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 polygon geometries on the map.

      Parameters

      • geometries: PolygonFeatures

        The polygon features to display, as a FeatureCollection.

      Returns Promise<void>

      • Replaces any previously shown geometries
      • Applies current module styling configuration
      • Waits for module to be ready before displaying
      • Automatically handles both Polygon and MultiPolygon types

      Feature properties:

      • title: The text of the center and border labels, unless label.title or lineLabel.title sets theirs. Without one, a text label.title, then address.freeformAddress, fills it in
      • color: Override fill colour per feature
      • fillStyle: Override the module's fill.style per feature
      • id: The id that event states and event handlers use, generated when missing. A feature's top-level id isn't read, so the top-level id of a geometry data result matches nothing
      • Custom properties accessible in styling expressions

      Single polygon:

      await geometries.show({
      type: 'FeatureCollection',
      features: [
      {
      type: 'Feature',
      bbox: [4.88, 52.37, 4.89, 52.38],
      geometry: {
      type: 'Polygon',
      coordinates: [[[4.88, 52.37], [4.89, 52.37], [4.89, 52.38], [4.88, 52.37]]]
      },
      properties: {
      title: 'Amsterdam Center',
      color: '#FF5733'
      }
      }
      ]
      });

      Multiple polygons:

      await geometries.show({
      type: 'FeatureCollection',
      features: [
      { type: 'Feature', geometry: {...}, properties: {...} },
      { type: 'Feature', geometry: {...}, properties: {...} }
      ]
      });

      From a place's geometry:

      import { geocodeOne, geometryData } from '@tomtom-org/maps-sdk/services';

      const amsterdam = await geocodeOne('Amsterdam');
      await geometries.show(await geometryData({ geometries: [amsterdam] }));
    • 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

      Use it for settings your code writes, as applyConfig: typed, and not checked at run time. To change nested values and keep the ones beside them, or to set values held as data, use setKnobs, which reaches each by its path and checks it.

      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 for any interaction, then creates an instance of the module.

      Parameters

      Returns Promise<GeometriesModule>

      GeometriesModule owns the sources and layers it adds, all suffixed per instance. Every call therefore returns a new, independent instance, so you can put several on the same map, each managing a different set of geometries with different styles.

      Default initialization:

      const geometriesModule = await GeometriesModule.create(map);
      

      With custom styling:

      const geometriesModule = await GeometriesModule.create(map, {
      fill: { color: 'blue', opacity: 0.25 },
      line: { color: 'darkblue', width: 2, opacity: 0.8 },
      label: {
      title: ['get', 'title']
      },
      beforeLayerConfig: 'top'
      });

      Data-driven styling:

      const geometriesModule = await GeometriesModule.create(map, {
      fill: {
      // Color based on feature properties
      color: [
      'match',
      ['get', 'type'],
      'residential', '#FFEB3B',
      'commercial', '#2196F3',
      'industrial', '#9E9E9E',
      '#E0E0E0' // default
      ],
      opacity: 0.4
      }
      });