Get Features Under the Mouse Pointer
Use queryRenderedFeatures() to inspect which map features are under the cursor on click or hover.
Click on any visible map feature to inspect it.
queryRenderedFeatures
Query all features visible at a point or within a bounding box:
javascript
// Query at mouse click point
map.on('click', (e) => {
const features = map.queryRenderedFeatures(e.point);
console.log(features); // array of all features at that pixel
});
// Query only specific layers
map.on('click', (e) => {
const features = map.queryRenderedFeatures(e.point, {
layers: ['my-layer']
});
});
// Query within a bounding box (pixel area)
const bbox = [[x1, y1], [x2, y2]];
const features = map.queryRenderedFeatures(bbox, {
layers: ['my-layer']
});querySourceFeatures
Query features directly from a source (including off-screen):
javascript
const features = map.querySourceFeatures('my-source', {
sourceLayer: 'my-source-layer', // for vector tile sources
filter: ['==', 'category', 'restaurant']
});Complete Example
html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<link href="https://cdn.mapmetrics-atlas.net/versions/latest/mapmetrics-gl.css" rel="stylesheet" />
<script src="https://cdn.mapmetrics-atlas.net/versions/latest/mapmetrics-gl.js"></script>
<style>#map { height: 500px; width: 100%; }</style>
</head>
<body>
<div id="map"></div>
<pre id="info" style="padding:10px;background:#f8fafc;border:1px solid #e2e8f0;"></pre>
<script>
const map = new mapmetricsgl.Map({ container: 'map', style: '<StyleFile_URL_with_Token>', center: [2.35, 48.85], zoom: 5 });
map.on('click', (e) => {
const features = map.queryRenderedFeatures(e.point);
document.getElementById('info').textContent = features.length
? JSON.stringify(features[0].properties, null, 2)
: 'No features found';
});
</script>
</body>
</html>jsx
import React, { useEffect, useRef, useState } from 'react';
import mapmetricsgl from '@mapmetrics/mapmetrics-gl';
import '@mapmetrics/mapmetrics-gl/dist/mapmetrics-gl.css';
const GetFeatures = () => {
const mapContainer = useRef(null);
const map = useRef(null);
const [info, setInfo] = useState('Click on the map to inspect features');
useEffect(() => {
if (map.current) return;
map.current = new mapmetricsgl.Map({ container: mapContainer.current, style: '<StyleFile_URL_with_Token>', center: [2.35, 48.85], zoom: 5 });
map.current.on('click', (e) => {
const features = map.current.queryRenderedFeatures(e.point);
setInfo(features.length ? JSON.stringify(features[0].properties, null, 2) : 'No features found');
});
return () => { map.current?.remove(); map.current = null; };
}, []);
return (
<div>
<div ref={mapContainer} style={{ height: '500px', width: '100%' }} />
<pre style={{ padding: '10px', background: '#f8fafc', border: '1px solid #e2e8f0', marginTop: '8px' }}>{info}</pre>
</div>
);
};
export default GetFeatures;For more information, visit the MapMetrics GitHub repository.