|
| 1 | +import { forwardRef, useEffect, useMemo, useRef, useState } from 'react'; |
| 2 | + |
| 3 | +import { |
| 4 | + MarkerClusterer as MarkerClustererClass, |
| 5 | + MarkerClustererOptions, |
| 6 | +} from '@googlemaps/markerclusterer'; |
| 7 | + |
| 8 | +import { passRef } from '../../utils/passRef'; |
| 9 | +import { useMapContext } from '../Provider/MapProvider'; |
| 10 | +import { MarkerClustererProps } from './type'; |
| 11 | +import { MarkerClustererProvider } from './Context'; |
| 12 | + |
| 13 | +const createMarkerClusterer = (options: MarkerClustererOptions) => |
| 14 | + new MarkerClustererClass(options); |
| 15 | + |
| 16 | +export const MarkerClusterer = forwardRef< |
| 17 | + MarkerClustererClass, |
| 18 | + MarkerClustererProps |
| 19 | +>(function MarkerClusterer( |
| 20 | + { children, algorithmOptions, algorithm, renderer, onClusterClick }, |
| 21 | + ref, |
| 22 | +) { |
| 23 | + const map = useMapContext(); |
| 24 | + const markers = useRef( |
| 25 | + new Set<google.maps.Marker | google.maps.marker.AdvancedMarkerElement>(), |
| 26 | + ); |
| 27 | + const markerCluster = useRef( |
| 28 | + createMarkerClusterer({ |
| 29 | + map, |
| 30 | + algorithmOptions, |
| 31 | + algorithm, |
| 32 | + renderer, |
| 33 | + onClusterClick, |
| 34 | + }), |
| 35 | + ); |
| 36 | + |
| 37 | + const value = useMemo( |
| 38 | + () => ({ |
| 39 | + addMarker: (marker) => ( |
| 40 | + markers.current.add(marker), markerCluster.current.addMarker(marker) |
| 41 | + ), |
| 42 | + removeMarker: (marker) => ( |
| 43 | + markers.current.delete(marker), |
| 44 | + markerCluster.current.removeMarker(marker) |
| 45 | + ), |
| 46 | + }), |
| 47 | + [], |
| 48 | + ); |
| 49 | + |
| 50 | + useEffect(() => { |
| 51 | + passRef(ref, markerCluster.current); |
| 52 | + }, []); |
| 53 | + |
| 54 | + useEffect(() => { |
| 55 | + markerCluster.current.setMap(null); |
| 56 | + markerCluster.current = createMarkerClusterer({ |
| 57 | + map, |
| 58 | + markers: Array.from(markers.current), |
| 59 | + algorithmOptions, |
| 60 | + algorithm, |
| 61 | + renderer, |
| 62 | + onClusterClick, |
| 63 | + }); |
| 64 | + }, [algorithmOptions, algorithm, renderer, onClusterClick]); |
| 65 | + |
| 66 | + return ( |
| 67 | + <MarkerClustererProvider value={value}>{children}</MarkerClustererProvider> |
| 68 | + ); |
| 69 | +}); |
0 commit comments