Tengo un problema al renderizar marcadores y agruparlos. Cuando obtengo la lista de datos de ubicación de la API por completo, el mapa no vuelve a representar el marcador.
Cuando uso un componente secundario de marcador personalizado, eso puede volver a representar el mapa cuando la API se recupera por completo. Pero no puedo agrupar estos marcadores personalizados.
Como sé, onGoogleApiLoaded solo llamó una vez en el primer renderizado, por lo que ahora no tengo una solución para resolver este problema.
Aquí mi código a continuación. Gracias por cualquier ayuda.
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>Una solución sería hacer que setGoogleMapRef no hiciera nada más que almacenar el map y los maps en algún estado, y luego tener un useEffect separado que crea el MarkerClusterer . Esto garantizará que el agrupador no se cree hasta que se carguen tanto el mapa como los datos (y se volverá a crear si los datos cambian). Algo así como:
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]); Alternativamente, si está dispuesto a buscar un paquete diferente, @react-google-maps/api tiene un componente para el agrupador, así como el mapa, el marcador, etc.:
<GoogleMap ...> <MarkerClusterer ...> {clusterer => unitLocations.map((location, index) => { <Marker position={location} clusterer={clusterer}/> } </MarkerClusterer> </GoogleMap >