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?
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.
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.