I have the following code in my React class which sets the center position of the map as expected. My issue is that when my componentDidMount completes I want to reset the center position of the map using values returned from my API.
This is what I'm trying to achieve -
- Load default map center position when the page is loading (this is working)
- When my API returns then re-center the map using the values returned from the API (this doesn't seem to work)
- Create a pin on the map using the same values returned from the API (this is working)
The code is included below. I've tried lots of attempts but I can't get it working as I've detailed above. Is there something I'm missing? I just can't seem to re-center the map.
Thanks,
React class
class Example extends Component {
constructor(props) {
super(props);
this.state = {
center: {
lat: 100,
lng: 100
}
};
Inside my componentDidMount function
var self = this;
Promise.all([callMyApi()]).then(([result]) => {
// Set map center location
self.setState(prevState => {
let mapCenter = Object.assign({}, prevState.center);
mapCenter.lat = result.latitude;
mapCenter.lng = result.longitude;
return { mapCenter };
});
// Set pin location
var pinArray = [];
pinArray.push({
"id": "1",
"latitude": result.latitude,
"longitude": result.longitude
});
self.setState({pins: pinArray});
Usage of the react map
const Pin = ({ profile }) => <div className={"pin"}><img src=".." /></div>;
<GoogleMapReact
bootstrapURLKeys={{ key: "" }}
defaultCenter={this.state.center} >
{this.state.pins.map(p => (
<Pin
key={p._id}
lat={p.latitude}
lng={p.longitude}
profile={p}
/>
))}
Attempt #1
self.setState({
center: {
lat: result.latitude,
lng: result.longitude
}
});