Merged in feat/SW-1616-clustering (pull request #1330)
feat(SW-1616): Added clustering on destination country/city pages * feat(SW-1616): Added clustering on destination country/city pages Approved-by: Fredrik Thorsson Approved-by: Matilda Landström
This commit is contained in:
@@ -0,0 +1,42 @@
|
||||
import { useEffect, useMemo, useReducer } from "react"
|
||||
import Supercluster, {type ClusterProperties } from "supercluster"
|
||||
|
||||
import { useMapViewport } from "./use-map-viewport"
|
||||
|
||||
import type { FeatureCollection, GeoJsonProperties, Point } from "geojson"
|
||||
|
||||
export function useSupercluster<T extends GeoJsonProperties>(
|
||||
geojson: FeatureCollection<Point, T>,
|
||||
superclusterOptions: Supercluster.Options<T, ClusterProperties>
|
||||
) {
|
||||
// create the clusterer and keep it
|
||||
const clusterer = useMemo(() => {
|
||||
return new Supercluster(superclusterOptions)
|
||||
}, [superclusterOptions])
|
||||
|
||||
// version-number for the data loaded into the clusterer
|
||||
// (this is needed to trigger updating the clusters when data was changed)
|
||||
const [version, dataWasUpdated] = useReducer((x: number) => x + 1, 0)
|
||||
|
||||
// when data changes, load it into the clusterer
|
||||
useEffect(() => {
|
||||
clusterer.load(geojson.features)
|
||||
dataWasUpdated()
|
||||
}, [clusterer, geojson])
|
||||
|
||||
// get bounding-box and zoomlevel from the map
|
||||
const { bbox, zoom } = useMapViewport({ padding: 100 })
|
||||
|
||||
// retrieve the clusters within the current viewport
|
||||
const clusters = useMemo(() => {
|
||||
// don't try to read clusters before data was loaded into the clusterer (version===0),
|
||||
// otherwise getClusters will crash
|
||||
if (!clusterer || version === 0) return []
|
||||
|
||||
return clusterer.getClusters(bbox, zoom)
|
||||
}, [version, clusterer, bbox, zoom])
|
||||
|
||||
return {
|
||||
clusters,
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user