JSFiddle - React, Tailwind, and code Playground

by Tristen Brown

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">
<link rel="stylesheet" href="https://api.mapbox.com/mapbox-assembly/mbx/v1.2.0/assembly.min.css">
<div id="map" class="absolute top bottom left right w-full"></div>

JavaScript

mapboxgl.accessToken =
  "pk.eyJ1IjoibWFwYm94c2F0ZWxsaXRlIiwiYSI6ImNqZWZ0MHg0djFqZWoyeG9kN3ZiMmkyd3cifQ.y2HNjGo7FcKQ7psI_BfGqQ"

const style = {
  version: 8,
  center: [-79.3819, 43.6449],
  zoom: 15.5,
  sources: {
    composite: {
      url: "mapbox://mapbox.mapbox-streets-v8",
      type: "vector",
    },
  },
  imports: [
    {
      id: "basemap",
      url: "mapbox://styles/mapbox/standard"
    }
  ],
  glyphs: "mapbox://fonts/mapbox/{fontstack}/{range}.pbf",
  projection: { name: "globe" },
  layers: [
    {
      id: "building",
      type: "fill",
      source: "composite",
      "source-layer": "building",
      paint: {
        "fill-color": [
          "case",
          ["to-boolean", ["feature-state", "click"]],
          "blue",
          ["to-boolean", ["feature-state", "hover"]],
          "red",
          "#000000",
        ],
				"fill-opacity": [
          "case",
          ["to-boolean", ["feature-state", "click"]],
          0.5,
          1
        ]
      },
    },
  ],
}

const map = (window.map = new mapboxgl.Map({
  container: "map",
  hash: true,
  style,
}))

map.doubleClickZoom.disable()

const onClick = () => {
  let feature = null
  return (e) => {
    if (feature) {
      map.setFeatureState(feature, { click: false })
      feature = null
    } else {
      map.setFeatureState(e.feature, { click: true })
      feature = e.feature
    }
  }
}

const onHover = () => {
  let feature = null
  map.addInteraction("building-out", {
    type: "mouseleave",
    featureset: { layerId: "building" },
    handler: (e) => {
      if (feature) {
        map.setFeatureState(feature, { hover: false })
        feature = null
      }
    },
  })

  return (e) => {
    if (feature) {
      map.setFeatureState(feature, { hover: false })
      feature = null
    }

    map.setFeatureState(e.feature, { hover: true })
    feature = e.feature
  }
}

map.addInteraction("building-click", {
  type: "click",
  featureset: { layerId: "building" },
  handler:...