Setting initial center for map from Web API on a React / google-maps-react component

1.6k views Asked by At

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?

1

There are 1 answers

0
Pagemag On

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 the center 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 the center 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:

import React, { Component } from "react";
import { Map, GoogleApiWrapper } from "google-maps-react";

export class MapContainer extends Component {
  state = {
    center: {
      lat: 40.854885,
      lng: -88.081807
    }
  };

  componentDidMount() {
    let newLat = {
      lat: 0,
      lng: 0
    };
    this.setState({ center: newLat });
  }
  render() {
    if (!this.props.loaded) return <div>Loading...</div>;

    return (
      <div>
        <div>
          center value: {this.state.center.lat} , {this.state.center.lng}
        </div>
        <Map
          className="map"
          google={this.props.google}
          onClick={this.onMapClicked}
          center={this.state.center}
          style={{ height: "100%", position: "relative", width: "100%" }}
          zoom={8}
        />
      </div>
    );
  }
}
export default GoogleApiWrapper({
  apiKey: "API_KEY"
})(MapContainer);