Skip to main content

Polygon Popup on Click

When a user clicks a polygon, show a popup containing more information. Requires Trimble Maps v3.0.0 or later.


<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Polygon popup on click</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="stylesheet" href="https://maps-sdk.trimblemaps.com/v4/trimblemaps-4.2.3.css" />
    <script src="https://maps-sdk.trimblemaps.com/v4/trimblemaps-4.2.3.js"></script>
    <style>
      body {
        margin: 0;
        padding: 0;
      }
      html,
      body,
      #map {
        height: 100%;
      }
      .trimblemaps-popup {
        max-width: 400px;
        font: 12px/20px system-ui, sans-serif;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>
    <script>
      TrimbleMaps.setAPIKey('YOUR_API_KEY_HERE');
      const map = new TrimbleMaps.Map({
        container: 'map',
        style: TrimbleMaps.Common.Style.TRANSPORTATION,
        center: [-100.04, 38.907],
        zoom: 3,
      });

      map.on('load', () => {
        // Add a source for the state polygons.
        map.addSource('states', {
          type: 'geojson',
          data: 'https://developer.trimblemaps.com/maps-sdk/aseets/ne_110m_admin_1_states_provinces_shp.geojson',
        });

        // Add a layer showing the state polygons.
        map.addLayer({
          id: 'states-layer',
          type: 'fill',
          source: 'states',
          paint: {
            'fill-color': 'rgba(200, 100, 240, 0.4)',
            'fill-outline-color': 'rgba(200, 100, 240, 1)',
          },
        });

        // When a click event occurs on a feature in the states layer, open a popup at the
        // location of the click, with description HTML from its properties.
        map.on('click', 'states-layer', (e) => {
          new TrimbleMaps.Popup()
            .setLngLat(e.lngLat)
            .setHTML(e.features[0].properties.name)
            .addTo(map);
        });

        // Change the cursor to a pointer when the mouse is over the states layer.
        map.on('mouseenter', 'states-layer', () => {
          map.getCanvas().style.cursor = 'pointer';
        });

        // Change it back to a pointer when it leaves.
        map.on('mouseleave', 'states-layer', () => {
          map.getCanvas().style.cursor = '';
        });
      });
    </script>
  </body>
</html>

Last updated June 26, 2025.