I am using the google-maps-react library and have a question about retrieving the latitude / longitude coordinates from a Web API to populate the map center when the component loads. I am able to see that the Web API call is being successfully made and returning the values I expect using a console.log() statement, but the map is not being updated with the values. I suspect it has to do with timing, but I'm not sure where the problem is.
I have tried the following code in the constructor and the componentDidMount() method. Both retrieve the values, but neither work by refreshing the map. I imagine this is a misunderstanding on my part of React's event / state handling:
componentDidMount() {
const initialBoundingBoxapiUrl = 'https://localhost:44395/api/User/abc';
fetch(initialBoundingBoxapiUrl)
.then((response) => response.json())
.then((data) => {
console.log('Data returned = ' + data);
var values = data.split(',');
// this.state.lat = values[0];
// this.state.lng = values[1];
this.setState({lat: values[0]});
this.setState({lng: values[1]});
});
}
state = {
lat: "40.0",
lng: "-74.0"
};
I have tried both updating the state values directly and using the setState() method.
If I set the "lat" and "lng" state values manually instead of trying to populate them from the fetch() method in either the constructor or componentDidMount(), the center is updated as I would expect.
My component looks like this:
<Map
apiKey={'allworkandnoplaymakesscottadullboy'}
google={this.props.google}
initialCenter={{
lat: this.state.lat,
lng: this.state.lng
}}
zoom={13}>
Where have my efforts gone astray?
It looks like the reason why the map is not being updated to center in the new center state is because you are using the
initialCenter
parameter and not thecenter
parameter. As you see,initialCenter
will only set the initial center of the map upon loading that's why it is only returning the initial value of your center state. To do this, you can use thecenter
parameter to re-render the map after the initial render. These were mentioned here.As a sample, you can see the following sample code when using the initialCenter and center when changing the center state value in componentDidMount.
CodeSnippet: