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
December 13, 2024
HTML
<script src="https://api.mapbox.com/mapbox-gl-js/v3.8.0/mapbox-gl.js"></script>
<link rel="stylesheet" href="https://api.mapbox.com/mapbox-gl-js/v3.8.0/mapbox-gl.css">
<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 style = {
version: 8,
name: "xray",
glyphs: "mapbox://fonts/mapbox/{fontstack}/{range}.pbf",
layers: [
{
id: "bg",
type: "background",
paint: {
"background-color": "#000",
},
},
{
id: "model:mapbox.mapbox-3dbuildings-v1:foobar:defocused",
source: "mapbox.mapbox-3dbuildings-v1",
type: "model",
paint: {
"model-color": "rgba(238, 78, 139, .75)",
"model-color-mix-intensity": 1,
"model-opacity": 0.5,
},
minzoom: 0,
maxzoom: 22
},
{
id: "model:mapbox.mapbox-3dbuildings-v1:foobar",
source: "mapbox.mapbox-3dbuildings-v1",
type: "model",
paint: {
"model-color": "rgb(91, 255, 142)",
"model-color-mix-intensity": 1,
"model-opacity": 0.5,
},
minzoom: 14,
maxzoom: 22
},
],
sources: {
"mapbox.mapbox-3dbuildings-v1": {
minzoom: 14,
maxzoom: 14,
tiles: [
"https://a.tiles.mapbox.com/3dtiles/v1/mapbox.mapbox-3dbuildings-v1/{z}/{x}/{y}.glb?access_token=pk.eyJ1IjoidHJpc3RlbiIsImEiOiJjajZoOXU4Z2kwNnppMnlxd2d6bTFvZ2xtIn0.PP7AoUakMfeqdXFHdsY0oA",
"https://b.tiles.mapbox.com/3dtiles/v1/mapbox.mapbox-3dbuildings-v1/{z}/{x}/{y}.glb?access_token=pk.eyJ1IjoidHJpc3RlbiIsImEiOiJjajZoOXU4Z2kwNnppMnlxd2d6bTFvZ2xtIn0.PP7AoUakMfeqdXFHdsY0oA",
],
type: "batched-model",
}
},
projection: {
name: "globe",
},
}
const map = new mapboxgl.Map({
container: "map",
style,
center: [-79.38048, 43.64929],
zoom: 14,
})
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",
]
...