Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Geocode in react app not updating the map React

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%20Tower&key=KEY&language=en".

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading