Skip to content
Documentation menu
docs / examples / hover-highlight
Example

Hover highlight with feature-state

Highlight the polygon under the pointer without touching the data. DataLayer flips a feature-state flag on one feature and its paint expressions read it, so hover costs no setData and no re-tiling, even on large sources.

ts
import { createMap, DataLayer } from "@mapmap/maps";

const map = createMap({
  container: "map",
  apiKey: "snk_...",
  attributionPosition: "bottom-left",
  center: [-0.12, 51.5],
  zoom: 10.3,
});
await map.whenReady();

const cells: GeoJSON.Feature[] = [];
for (let x = 0; x < 18; x++) {
  for (let y = 0; y < 12; y++) {
    const west = -0.42 + x * 0.034, south = 51.36 + y * 0.025;
    cells.push({
      type: "Feature",
      properties: { cell: x * 100 + y },
      geometry: {
        type: "Polygon",
        coordinates: [[
          [west, south], [west + 0.034, south], [west + 0.034, south + 0.025],
          [west, south + 0.025], [west, south],
        ]],
      },
    });
  }
}

// Hover is on by default: the cell under the pointer brightens and the
// cursor turns to a pointer. select: "multi" lets a click toggle cells.
const areas = new DataLayer(map, {
  data: { type: "FeatureCollection", features: cells },
  // feature-state needs a stable id per feature: promote one of yours.
  promoteId: "cell",
  style: { simple: { color: "#1a6bff", opacity: 0.12, width: 0.6 } },
  select: "multi",
});

areas.on("hover", ({ feature }) => {
  console.log(feature ? "over cell " + feature.properties.cell : "left the grid");
});
areas.on("select", ({ selected }) => {
  console.log(selected.length + " cells selected");
});

Worth knowing

  • feature-state is only readable from paint properties, never from layout or filter. DataLayer uses it for colour, opacity and width; use setFilter or setData for anything that changes which features draw.
  • Ids must be stable. On GeoJSON use promoteId (a property) or feature.id; data without either gets generated ids, which hover and select fine but renumber on every setData. On a pmtiles:// source the id must be the same on every tile the feature crosses.
  • For basemap features (POIs, place labels, buildings) use map.addInteraction with a featureset instead: see the interactions example.