JSFiddle - React, Tailwind, and code Playground
by askhflajsf
HTML
<link rel="stylesheet" href="https://raw.githubusercontent.com/mapbox/mapbox-gl-js/main/src/css/mapbox-gl.css">
<div id="map" data-cars="" data-mapbox-api-key="pk.eyJ1Ijoicm9kbG9ib3oiLCJhIjoiY2p1dDk1OTE3MDVrcjN5cGZvbDMxYTk2ZCJ9.KXSCGCgM-5YgWXKmzWLtWg">
</div>
JavaScript
import 'mapbox-gl/dist/mapbox-gl.css';
import mapboxgl from 'mapbox-gl';
const fitMapToMarkers = (map, features) => {
const bounds = new mapboxgl.LngLatBounds();
features.forEach(({
geometry
}) => bounds.extend(geometry.coordinates));
map.fitBounds(bounds, {
padding: 70,
maxZoom: 15
});
};
const initMapbox = () => {
const mapElement = document.getElementById('map');
if (mapElement) {
mapboxgl.accessToken = mapElement.dataset.mapboxApiKey;
const map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v10',
zoom: 30
});
map.on('load', function() {
const cars = JSON.parse(mapElement.dataset.cars);
map.addSource('cars', {
type: 'geojson',
data: cars,
cluster: true,
clusterMaxZoom: 14,
clusterRadius: 50
});
map.addLayer({
id: 'clusters',
type: 'circle',
source: 'cars',
filter: ['has', 'point_count'],
paint: {
'circle-color': [
'step',
['get', 'point_count'],
'#51bbd6',
100,
'#f1f075',
750,
'#f28cb1'
],
'circle-radius': [
'step',
['get', 'point_count'],
20,
100,
30,
750,
40
]
}
});
map.addLayer({
id: 'cluster-count',
type: 'symbol',
source: 'cars',
filter: ['has', 'point_count'],
layout: {
'text-field': '{point_count_abbreviated}',
'text-font': ['DIN Offc Pro Medium', 'Arial Unicode MS Bold'],
'text-size': 12
}
});
map.addLayer({
id: 'unclustered-point',
type: 'circle',
source: 'cars',
filter: ['!', ['has', 'point_count']],
paint: {
'circle-color': '#11b4da',
'circle-radius': 10,
...