I use such a pattern to get user's current position:
componentDidMount() {
let lat, lon;
navigator.geolocation.getCurrentPosition(function(location) {
lat = location.coords.latitude;
lon = location.coords.longitude;
});
setTimeout(() => {
this.setState({
lat,
lon
})
console.log(this.state.lon, this.state.lat);
}, 1000);
}
It actually works but looks "patchy" because of setTimeout
.
The core problem is in some delay of getting location and console throws undefined
without setTimeout
.
I tried a few another ways to fix it but all failed:
navigator.geolocation.getCurrentPosition(function(location) {
this.setState({
lat: location.coords.latitude,
lon: location.coords.longitude
})
}).bind(this);
and humble let _this = this
for example.
Please, is there more wise way to setState
, based on geolocation?