I want to get location information by using Geolocation API
in react.
I made a button
to get location info in this code.
import React, { Component } from 'react'
class App extends Component {
constructor(props) {
super(props)
this.state = {
latitude: null,
longitude: null,
}
}
position = async () => {
await navigator.geolocation.getCurrentPosition(
position => this.setState({
latitude: position.coords.latitude,
longitude: position.coords.longitude
}),
err => console.log(err)
);
console.log(this.state.latitude)
}
render() {
return (
<div>
<button onClick={this.position} className='Filter'>Filter</button>
</div>
);
}
}
export default App;
Once I pressed a button
, console shows null
.
However, when I pressed a button
again, the console shows location info.
Do you have any idea why I couldn't get the location info for the first time?