I am getting the user's location in componentDidMount, and it works well. However, after that, I am trying to change the state, and it does not register the change. Here is my constructor:
constructor(props){
super(props);
this.locationRetrieved = this.locationRetrieved.bind(this);
this.state = {
latitude: 30,
longitude: 30
}
}
and my locationRetreived function (hardcoding these for now):
locationRetrieved() {
this.setState({
latitude: 78,
longitude: 89
});
}
and my componentDidMount:
componentDidMount() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(success) {
this.locationRetrieved();
},
function(failure) {
alert(failure);
if(failure.message.indexOf("Only secure origins are allowed") == 0) {
// Secure Origin issue.
}
});
}
else{
alert("gelocation is not supported here");
}
}
I have also tried directly setting state and not calling a function, like:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(success) {
this.setState({
latitude: 45,
longitude: 45
})
},
but that does not work either. I know a location is retrieved, because when I do alert(success.coords.latitude) then the alert with my current latitude shows up.
The error console says:
Uncaught TypeError: Cannot read property 'locationRetrieved' of undefined
at eval (eval at ./app/containers/CheckIn/index.js
How can I set the state here once latitude/longitude are retrieved?
Thanks