Back to all examples

Geometries playground

Display multiple geographic geometries with different configurations

import type { Places } from '@tomtom-org/maps-sdk/core';
import { TomTomConfig } from '@tomtom-org/maps-sdk/core';
import {
    GeometriesModule,
    type GeometryBeforeLayerConfig,
    type StandardStyleID,
    standardStyleIDs,
    TomTomMap,
} from '@tomtom-org/maps-sdk/map';
import { geocode, geometryData } from '@tomtom-org/maps-sdk/services';
import type { LngLatBoundsLike } from 'maplibre-gl';
import type { Config } from './placeConfiguration';
import { namedConfigs } from './placeConfiguration';
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' });

(async () => {
    const fitBoundsOptions = { padding: 50 };

    const map = new TomTomMap({ container: 'sdk-map', fitBoundsOptions });
    const geometryModule = await GeometriesModule.get(map);
    let placeSubdivisions: Places;

    const updateMap = async (config: Config) => {
        placeSubdivisions = await geocode({ limit: 100, query: '', ...config.searchConfig });
        map.mapLibreMap.fitBounds(placeSubdivisions.bbox as LngLatBoundsLike, fitBoundsOptions);
        const geometries = await geometryData({ geometries: placeSubdivisions, zoom: 14 });
        geometryModule.applyConfig(config.geometryConfig);
        geometryModule.show(geometries);
    };

    const listenToUIEvents = async () => {
        const placeSelector = document.getElementById('sdk-example-place-selector') as HTMLSelectElement;
        placeSelector.addEventListener('change', (event) =>
            updateMap(namedConfigs[(event.target as HTMLInputElement).value]),
        );

        const options = document.querySelectorAll<HTMLInputElement>('input[type=radio][name=layerOption]');
        options.forEach((option) => {
            option.addEventListener('change', () =>
                geometryModule.moveBeforeLayer(option.value as GeometryBeforeLayerConfig),
            );
        });

        const stylesSelector = document.querySelector('#sdk-example-mapStyles') as HTMLSelectElement;
        standardStyleIDs.forEach((id) => stylesSelector.add(new Option(id)));
        stylesSelector.addEventListener('change', (event) =>
            map.setStyle((event.target as HTMLOptionElement).value as StandardStyleID),
        );

        document
            .querySelector('#sdk-example-reCenter')
            ?.addEventListener(
                'click',
                () =>
                    placeSubdivisions &&
                    map.mapLibreMap.fitBounds(placeSubdivisions.bbox as LngLatBoundsLike, fitBoundsOptions),
            );
    };

    await updateMap(namedConfigs.france);
    await listenToUIEvents();
})();

Related examples