Skip to content

Get features under the mouse pointer

Use queryRenderedFeatures to show properties of hovered-over map elements.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Get features under the mouse pointer</title>
    <meta property="og:description" content="Use queryRenderedFeatures to show properties of hovered-over map elements." />
    <meta charset='utf-8'>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/trackasia-gl.css" />
    <script src="https://unpkg.com/[email protected]/dist/trackasia-gl.js"></script>
    <style>
        body { margin: 0; padding: 0; }
        html, body, #map { height: 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;
        }
    </style>
</head>
<body>

<div id="map"></div>
<pre id="features"></pre>
<script>
    const map = new trackasiagl.Map({
        container: 'map',
        style: 'https://maps.track-asia.com/styles/v1/streets.json?key=public_key',
        center: {"lat":10.762622,"lng":106.660172},
        zoom: 6
    });

    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;
        });

        document.getElementById('features').innerHTML = JSON.stringify(
            displayFeatures,
            null,
            2
        );
    });
</script>

</body>
</html>