Get features under the mouse pointer

Use queryRenderedFeatures to show properties of hovered-over map elements. See the example: https://docs.mapbox.com//mapbox-gl-js/example/queryrenderedfeatures/

by Tristen Brown

HTML

<link rel="stylesheet" href="https://api.mapbox.com/mapbox-gl-js/v3.0.0-rc.2/mapbox-gl.css">
<script src="https://api.mapbox.com/mapbox-gl-js/v3.0.0-rc.2/mapbox-gl.js"></script>


<div id="map"></div>
<pre id="features"></pre>

CSS

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

    #features {
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        width: 50%;
        overflow: auto;
        background: rgba(255, 255, 255, 0.8);
    }
    #map canvas {
        cursor: crosshair;
    }

JavaScript

mapboxgl.accessToken = 'pk.eyJ1IjoidHJpc3RlbiIsImEiOiJjajZoOXU4Z2kwNnppMnlxd2d6bTFvZ2xtIn0.PP7AoUakMfeqdXFHdsY0oA';
    const map = new mapboxgl.Map({
        container: 'map',
        style: 'mapbox://styles/mapbox/standard',
        center: [-96, 37.8],
        zoom: 3
    });

    map.on('mousemove', (e) => {
        const features = map.queryRenderedFeatures(e.point);

        // Limit the number of properties we're displaying for
        // legibility and performance
        const displayProperties = [
            'type',
            'properties',
            'id',
            'layer',
            'source',
            'sourceLayer',
            'state'
        ];

        const displayFeatures = features.map((feat) => {
            const displayFeat = {};
            displayProperties.forEach((prop) => {
                displayFeat[prop] = feat[prop];
            });
            return displayFeat;
        });

        // Write object as string with an indent of two spaces.
        document.getElementById('features').innerHTML = JSON.stringify(
            displayFeatures,
            null,
            2
        );
    });