Home > Blockchain >  Geocode in react app not updating the map React
Geocode in react app not updating the map React

Time:06-03

I'm trying to get the map geocode but when the map is loading it never uses the new lat and lng. It's always the original one from the useState.

const CustomMap = () => {
const [customLat, setCustomLat] = useState(0);
const [customLng, setCustomLng] = useState(0);

useEffect(() => {
    Geocode.fromAddress("Eiffel Tower").then(
        (response) => {
            const { lat, lng } = response.results[0].geometry.location;
            setCustomLat(lat);
            setCustomLng(lng);
        },
        (error) => {
            console.log(error.data);
        }
    );

}, [])

return (
    <GoogleMapReact
        bootstrapURLKeys={{ key: 'API_KEY' }}
        defaultCenter={{ lat: customLat, lng: customLng }}
        defaultZoom={11}>
    </GoogleMapReact>
)
}

Even though in the console I can see it's getting the map with url of the Eifell towel.

Fetch finished loading: GET "https://maps.googleapis.com/maps/api/geocode/json?address=Eiffel Tower&key=KEY&language=en".

That is the last console log but the center of the map is still the original ones.

CodePudding user response:

You are using the default, this only works on the first render, to update you need use the center, like this

  <GoogleMapReact
        bootstrapURLKeys={{ key: 'API_KEY' }}
        defaultCenter={{ lat: customLat, lng: customLng }}
        center = {{lat: customLat, lng: customLng}}
        defaultZoom={11}>
    </GoogleMapReact>

  • Related