A react hook for mapbox's supercluster library
const { clusters } = useSupercluster({
points: geojsonPoints,
bounds: mapBoundaries,
zoom: mapZoomLevel,
});
Easy, right? 😎
You need to have React 16.8.0 or later installed to use this library.
yarn
yarn add react-supercluster supercluster
npm
npm install --save react-supercluster supercluster
Typescript
If you use typescript, also install the type definitions @types/supercluster
.
You can find a working example in the folder example/
. The example uses pigeon-map for demonstration purpose, but you can use any map library you want.
Say you have a list of items:
const items = [
{
"id": "5d443711277ad1bb99d7db7d",
"name": "Your really cool stuff",
"coordinates": { "lat": 49.0214124, "lng": 11.2141024 }
},
...
]
Then you have to transform your list to the expected format, which is the following:
const geojsonPoints = items.map(item => {
return {
type: 'Feature',
properties: {
itemId: item.id,
},
geometry: {
type: 'Point',
coordinates: [item.coordinates.lng, item.coordinates.lat],
},
};
});
Then you can pass the points to useSupercluster
:
import useSupercluster from 'react-supercluster';
const { clusters } = useSupercluster({
points: geojsonPoints,
bounds: mapBoundaries,
zoom: mapZoomLevel,
});
<YourMap>
{clusters.map(cluster => {
if (cluster.properties.cluster) {
return <YourMapClusterMarker />;
}
return <YourMapPinMarker />;
})}
</YourMap>;
MIT © patlux