I have a issue when rendering markers and clustering them. When i fetch location data list from api completely, map doesn't re-render marker.
When i use custom marker child component, that can re-render map when api is fetch completely. But I can't Clustering these custom marker.
As i know that onGoogleApiLoaded just called once times at the first render so now I have no solution to solve this issue.
Here my code below. Thanks for any help.
const get_list_unit_location = useCallback(() => {
if (units.length) {
const listLocation = [];
units.forEach((unit) => {
if (unit.lat && unit.lng) {
listLocation.push({
lat: unit.lat,
lng: unit.lng,
subUnitQuantity: unit.sub_units.length,
});
}
});
setUnitLocations(listLocation);
}
}, [units]);
useEffect(() => {
get_list_unit_location();
}, [get_list_unit_location]);
const setGoogleMapRef = useCallback(
(map, maps) => {
if (unitLocations.length) {
const markers = unitLocations.map((location) => {
return new maps.Marker({ position: location, map });
});
// eslint-disable-next-line no-unused-vars
const markerCluster = new MarkerClusterer({ map, markers });
}
},
[unitLocations]
);
<GoogleMapReact
bootstrapURLKeys={{ key: process.env.REACT_APP_GOOGLE_MAP_API_KEY }}
defaultCenter={center}
defaultZoom={zoom}
options={{
fullscreenControl: false,
zoomControl: false,
}}
yesIWantToUseGoogleMapApiInternals
onGoogleApiLoaded={({ map, maps }) => setGoogleMapRef(map, maps)}
>
{unitLocations.map((location) => (
// eslint-disable-next-line react/jsx-key
<Marker
lat={location.lat}
lng={location.lng}
text={location.subUnitQuantity}
/>
))}
</GoogleMapReact>
One solution would be to have setGoogleMapRef do nothing more than store map and maps into some state, and then have a separate useEffect that creates the MarkerClusterer. This will ensure that the clusterer isn't created until both map and data are loaded (and will be recreated if the data changes.) Something like:
const [ map, setMap ] = useState();
const [ maps, setMaps ] = useState();
const setGoogleMapRef = useCallback((map, maps) => {
setMap(map);
setMaps(maps);
}, [ setMap, setMaps ]);
useEffect(() => {
if (unitLocations.length && map && maps) {
// create markers and clusterer
}
}, [ unitLocations, map, maps]);
Alternatively, if you're willing to look at a different package, @react-google-maps/api has a component for the clusterer as well as the map, marker, etc:
<GoogleMap ...>
<MarkerClusterer ...>
{clusterer => unitLocations.map((location, index) => {
<Marker position={location} clusterer={clusterer}/>
}
</MarkerClusterer>
</GoogleMap >