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",
},
},
glyphs: "mapbox://fonts/mapbox/{fontstack}/{range}.pbf",
projection: { name: "globe" },
layers: [
{
id: "building-1",
type: "fill",
source: "composite",
"source-layer": "building",
paint: {
"fill-color": [
"case",
["to-boolean", ["feature-state", "state"]],
"red",
"#000000",
]
}
},
{
id: "building-2",
type: "fill",
source: "composite",
"source-layer": "building",
paint: {
"fill-color": [
"case",
["to-boolean", ["feature-state", "state"]],
"green",
"blue",
]
}
}
]
}
const map = (window.map = new mapboxgl.Map({
container: "map",
hash: true,
style,
}))
map.doubleClickZoom.disable();
let feature;
const onClick = (e) => {
if (feature) {
map.setFeatureState(feature, { state: false });
feature = null;
} else {
map.setFeatureState(e.feature, { state: true });
feature = e.feature;
}
}
map.addInteraction("building-1-click", {
type: "click",
featureset: { layerId: 'building-1' },
handler: onClick
});