JCB90
JCB90

Reputation: 83

How do I get Geolocation API co-ordinates out of my nested function and into React state?

I'm trying to get a user's location using the Geolocation API when a user clicks a button:

<button onClick={this.setNewLatLong()}>"Use my location"</button>;

I can access the lat/long coordinates with the following code:

setNewLatLong = () => { 
 navigator.geolocation.getCurrentPosition(displayLocationInfo);

  function displayLocationInfo(position) {
      const longitude = position.coords.longitude;
      const latitude = position.coords.latitude;

      console.log(`long: ${longitude} | lat: ${latitude}`);
  }
}

But I can't get the data into my state because the latitude and longitude variables are too nested within functions.

How can I get this data into my state?

Upvotes: 0

Views: 295

Answers (2)

longhungn
longhungn

Reputation: 16

Every component state update in React should be done with setState(). For your case, you can use setState() in the callback function passed into getCurrentPosition().

navigator.geolocation.getCurrentPosition(position => {
    this.setState({
        lat: position.coords.latitude,
        lng: position.coords.longitude
    });
})

I would also recommend looking into using React hooks for state (after you have finished learning the basics of React)

Upvotes: 0

Arian Khosravi
Arian Khosravi

Reputation: 457

In React, you hold on the information in the component's state. You can set the state like so:

this.setState({
  lon: longitude,
  lat: latitude
})

And access the state from your view (render function), or any where else you may need it.

Upvotes: 0

Related Questions