How can I access the object of the navigator.geolocation.getCurrentPosition success callback outside the function when calling it?
Let say I have a function in a file(called UserLoc) which I am exporting.
export const locateCurrentPosition = () => {
const currentPosition = navigator.geolocation.getCurrentPosition(
position => {
console.log(position);
return position;
},
error => {
console.log(error.message);
return error;
},
{
enableHighAccuracy: true,
timeout: 10000,
maximumAge: 1000
}
);
return currentPosition;
};
Now on one of my component js files, I want to call this function inside the componentDidMount()
const {
locateCurrentPosition
} = require("../Views/components/User/UserMap/UserLoc");
async componentDidMount(){
console.log(locateCurrentPosition())
locateCurrentPosition().then(data=>console.log(data))
}
When I am calling the function inside my componentDidMount, it always returns an undefined. When Im logging this, it prints out the position when inside the local scope (ie first code block above where I use console.log(position). What is the best way to actually retrieve the position object from a successful callback and return it into my componentDidMount when called?
Ive tried promises, then statements with my console log as well as different types of returns, but I always seem to get undefined. The return statements within the locateCurrentPosition function dont seem to work. Any suggestions?
Added arrow after new Promise((resolve,reject)
navigator.geolocation.getCurrentPosition
returns undefined
, the value returned from calling locateCurrentPosition
. Position is only passed to the callback supplied in the call, which can be turned into a promise as required:
export const locateCurrentPosition = () => new Promise((resolve,reject)=> {
navigator.geolocation.getCurrentPosition(
position => {
console.log(position);
resolve(position);
},
error => {
console.log(error.message);
reject(error);
},
{
enableHighAccuracy: true,
timeout: 10000,
maximumAge: 1000
}
);
});
and called using
locateCurrentPosition().then(position=>console.log(position))
See also How do I return the response from an asynchronous call