Skip to main content

Highlight Selected Features

Select Places to highlight by holding shift and dragging a selection box over them.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <link rel="stylesheet" href="https://maps-sdk.trimblemaps.com/v3/trimblemaps-3.19.0.css" />
        <script src="https://maps-sdk.trimblemaps.com/v3/trimblemaps-3.19.0.js"></script>
        <style>
            body { margin: 0; padding: 0; }

            #map {
                position: absolute;
                top: 0;
                bottom: 0;
                width: 100%;
            }

            .boxdraw {
                background: rgba(56, 135, 190, 0.1);
                border: 2px solid #3887be;
                position: absolute;
                top: 0;
                left: 0;
                width: 0;
                height: 0;
            }
      </style>
      </head>
      <body>
          <div id="map"></div>
          <div class="filter-ctrl">
          <input
          id="filter-input"
          type="text"
          name="filter"
          placeholder="Filter by name"
          autocomplete="off"
          />
          </div>

      <script>
        TrimbleMaps.APIKey = 'YOUR_API_KEY_HERE';
        const myMap = new TrimbleMaps.Map({
            container: 'map', // container id
            style: TrimbleMaps.Common.Style.TRANSPORTATION, //hosted style id
            center: [-80.07256, 40.47625], // starting position
            zoom: 12, // starting zoom
            hash: true
        });

        myMap.boxZoom.disable();

        const popup = new TrimbleMaps.Popup()

        myMap.on('load', (e) => {

            const canvas = myMap.getCanvasContainer();
            let start;
            let current;
            let box;

            myMap.addLayer(
                {
                    'id': 'places-highlighted',
                    'type': 'fill',
                    'source': 'Places',
                    'source-layer': 'sites',
                    'paint': {
                        'fill-outline-color': '#484896',
                        'fill-color': '#6e599f',
                        'fill-opacity': 0.99
                    },
                    'filter': ['in', 'tpids', '']
                }
            );

            canvas.addEventListener('mousedown', mouseDown, true);
            function mousePos(e) {
                const rect = canvas.getBoundingClientRect();
                return new TrimbleMaps.Point(
                    e.clientX - rect.left - canvas.clientLeft,
                    e.clientY - rect.top - canvas.clientTop
                );
            }

            function mouseDown(e) {
                // Continue the rest of the function if the shiftkey is pressed.
                if (!(e.shiftKey && e.button === 0)) return;

                // Disable default drag zooming when the shift key is held down.
                myMap.dragPan.disable();

                // Call functions for the following events
                document.addEventListener('mousemove', onMouseMove);
                document.addEventListener('mouseup', onMouseUp);
                document.addEventListener('keydown', onKeyDown);

                // Capture the first xy coordinates
                start = mousePos(e);
            }

            function onMouseMove(e) {
                // Capture the ongoing xy coordinates
                current = mousePos(e);

                // Append the box element if it doesn't exist
                if (!box) {
                    box = document.createElement('div');
                    box.classList.add('boxdraw');
                    canvas.appendChild(box);
                }

                const minX = Math.min(start.x, current.x),
                    maxX = Math.max(start.x, current.x),
                    minY = Math.min(start.y, current.y),
                    maxY = Math.max(start.y, current.y);

                // Adjust width and xy position of the box element ongoing
                const pos = `translate(${minX}px, ${minY}px)`;
                box.style.transform = pos;
                box.style.width = maxX - minX + 'px';
                box.style.height = maxY - minY + 'px';
            }

            function onMouseUp(e) {
                // Capture xy coordinates
                finish([start, mousePos(e)]);
            }

            function onKeyDown(e) {
                // If the ESC key is pressed
                if (e.keyCode === 27) finish();
            }

            function finish(bbox) {
                // Remove these events now that finish has been called.
                document.removeEventListener('mousemove', onMouseMove);
                document.removeEventListener('keydown', onKeyDown);
                document.removeEventListener('mouseup', onMouseUp);

                if (box) {
                    box.parentNode.removeChild(box);
                    box = null;
                }

                // If bbox exists. use this value as the argument for `queryRenderedFeatures`
                if (bbox) {
                    var features = myMap.queryRenderedFeatures(bbox)
                    features = features.filter(function (item) {
                        if (item.layer.id == "places_sites") {
                            console.log(item)
                            return true
                        }
                        return false
                    });


                    if (features.length >= 1000) {
                        return window.alert('Select a smaller number of features');
                    }

                    // Run through the selected features and set a filter
                    // to match features with unique FIPS codes to activate
                    // the `counties-highlighted` layer.
                    const tpids = features.map((feature) => feature.properties.tpid);
                    myMap.setFilter('places-highlighted', ['in', 'tpid', ...tpids]);
                }

                myMap.dragPan.enable();
            }

            myMap.on('mousemove', (e) => {
                const features = myMap.queryRenderedFeatures(e.point, {
                    layers: ['places-highlighted']
                });

                // Change the cursor style as a UI indicator.
                myMap.getCanvas().style.cursor = features.length ? 'pointer' : '';

                if (!features.length) {
                    popup.remove();
                    return;
                }

                popup
                    .setLngLat(e.lngLat)
                    .setText(features[0].properties.COUNTY)
                    .addTo(myMap);
            });
        });


        </script>
    </body>
</html>
Last updated June 15, 2023.