Get features for MultiPolygon where dynamic === true

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

<script src="https://api.mapbox.com/mapbox-gl-js/v3.17.0/mapbox-gl.js"></script>
<link rel="stylesheet" href="https://api.mapbox.com/mapbox-gl-js/v3.17.0/mapbox-gl.css">
<div id="map"></div>

CSS

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

JavaScript

mapboxgl.accessToken =
  "pk.eyJ1IjoidHJpc3RlbiIsImEiOiJjajZoOXU4Z2kwNnppMnlxd2d6bTFvZ2xtIn0.PP7AoUakMfeqdXFHdsY0oA";

const data = {
  type: "FeatureCollection",
  features: [
    {
      id: 123,
      type: "Feature",
      properties: {},
      geometry: {
        type: "MultiPolygon",
        coordinates: [
          [
            [
              [-113.92486865140889, 36.190877423946745],
              [-102.96408959944262, 36.190877423946745],
              [-102.96408959944262, 44.52510350677309],
              [-113.92486865140889, 44.52510350677309],
              [-113.92486865140889, 36.190877423946745],
            ],
          ],
          [
            [
              [-100.38508276368611, 27.72295963047698],
              [-89.42430371171984, 27.72295963047698],
              [-89.42430371171984, 36.057185713303326],
              [-100.38508276368611, 36.057185713303326],
              [-100.38508276368611, 27.72295963047698],
            ],
          ],
        ],
      },
    },
  ],
};

const style = {
  version: 8,
  name: "Blank",
  imports: [
    {
      id: "basemap",
      url: "mapbox://styles/mapbox/standard",
      config: { theme: "monochrome" },
    },
  ],
  sources: {
    custom: {
      type: "geojson",
      data,
      dynamic: true,
    },
  },
  glyphs: "mapbox://fonts/mapbox/{fontstack}/{range}.pbf",
  projection: { name: "globe" },
  layers: [
    {
      id: "custom",
      source: "custom",
      type: "fill"
    },
  ],
};

const map = new mapboxgl.Map({
  container: "map",
  style,
  center: [-96.26, 36.64],
  zoom: 2.5,
});

let hoveredId = null;

map.on("mousemove", (e) => {
  const features = map.queryRenderedFeatures(e.point, { validate: false });
  console.log(features);
});