JSFiddle - React, Tailwind, and code Playground
by Tristen Brown
HTML
<link rel="stylesheet" href="https://api.mapbox.com/mapbox-assembly/mbx/v1.2.0/assembly.min.css">
<script src="https://api.mapbox.com/mapbox-gl-js/v3.9.0-beta.1/mapbox-gl.js"></script>
<link rel="stylesheet" href="https://api.mapbox.com/mapbox-gl-js/v3.9.0-beta.1/mapbox-gl.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-map-design/standard-experimental-ime"
}
],
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",
]
},
},
],
}
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",
target: { 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",
target: { layerId: "building" },
handler: onClick(),
})
map.addInteraction("building-hover", {
type: "mouseover",
target: { layerId: "building" },
...