crash springfield
crash springfield

Reputation: 1082

Can't set React state when getting user lat/long location

I'm trying to get the user's location (that works) and set it to the current state in a React component (this part doesn't). I've looked through a few answers on here and can't tell what I'm doing wrong.

Here's what I have:

class Container extends Component {
  constructor() {
    super()
    this.state = {
      location: {
        lat: 0,
        lng: 0
      }
    }
  }
  componentDidMount() {
    navigator.geolocation.getCurrentPosition(
      (position) => {
        let lat = position.coords.latitude
        let lng = position.coords.longitude
        console.log("getCurrentPosition Success " + lat + lng) // logs position correctly
        this.setState({
          location: {
            lat: lat,
            lng: lng
          }
        })
      },
      (error) => {
        this.props.displayError("Error dectecting your location");
        console.error(JSON.stringify(error))
      },
      {enableHighAccuracy: true, timeout: 20000, maximumAge: 1000}
    )
  }
  render() {
    const location = this.state.location
    return (
      <div>
         <Map center={location}/>
      </div>
    )
  }
}

It looks similar to what other people have, and I've tried a few different ways, but I can't get the state to set. Is there something I'm missing or doing wrong?

Upvotes: 0

Views: 1370

Answers (1)

Cesar Ho
Cesar Ho

Reputation: 183

The setState command is working fine.

enter image description here

Note that the get location is an async. call, and therefore the render() will be called twice. The first time it call, the lat/lng is zero.

You can add a logic to check it is zero and return null, if you want to render the output after getting the lat/lng from the geolocation services.

Upvotes: 1

Related Questions