Using GoogleMap API to display custom locations
I have an array of json object called data
imported; it has a property called address. Google map api looks up coordinates of the address property and should generates custom Markers from an array called locations.
But the value of locations inside fetchLocations()
and getCoordinates
, are different when I console.log, although the both represent the same variable.
What did I do wrong?
import React, { useEffect, useState } from 'react' import { GoogleMap, useLoadScript, InfoWindowF, MarkerF } from "@react-google-maps/api" import { data } from './data' const API_KEY = "1234567890" export default function MyComponent() { const { isLoaded }: any = useLoadScript({ googleMapsApiKey: API_KEY, }) const result : any[] = []; const [locations, setLocations] = useState(result); useEffect(() => { const fetchLocations = async () => { const locations = await Promise.all(data.map(getCoordinates)); console.log("Locations in fetchLocations", locations) }; fetchLocations(); }, []); const getCoordinates = async (obj: any) => { const objData = await fetch("https://maps.googleapis.com/maps/api/geocode/json?address=" + obj.address + '&key=' + API_KEY) const response = await objData.json() const latitude = response.results[0].geometry.location.lat; const longitude = response.results[0].geometry.location.lng; const position = { 'lat': latitude, 'lng': longitude } locations.push(position) console.log("Locations in get Cooordinate", locations) } if (!isLoaded) return <div>Loading...</div> return ( <div className='flex flex-col'> <GoogleMap zoom={11} center={{ lat: 35.685661305110415, lng: 139.75255896834707 }} mapContainerClassName='w-full h-[32em] m-2 rounded-lg' > <> {locations.map(location=>{ return( <> <MarkerF position={{ lat: location.lat, lng: location.lng }} /> </> ) }) } </> </GoogleMap> <button onClick={() => { setSelected(!selected) }}>Click</button> </div> ) }
Advertisement
Answer
The locations
array should never be changed in any way. It’s supposed to be immutable. The only thing that is able to change it is the setLocations
function.
Instead of locations.push(position)
do:
setLocations([...locations, position])
Also, getCoordinates
is not returning anything. It should return the same value sent to setLocations
:
return [...locations, position]