I've wrapped the geolocation API in the getLocation() function and am returning an array. However, when I try to access the specific elements of the array, I am getting undefined. I feel like I'm missing something very simple here.
const getLocation = function () {
const arrLocations = [];
navigator.geolocation.getCurrentPosition(function (position) {
arrLocations.push(position.coords.latitude)
arrLocations.push(position.coords.longitude)
});
return arrLocations;
}
const coord = getLocation();
console.log(coord);
console.log(coord[0]);
I've also tried to wrap the geolocation in a promise just in case there is some async happening with getCurrentPosition. The call returns undefined. (I'm not sure if I've written the promise right. I'm relatively new to JavaScript):
new Promise(function (resolve, reject) {
const arrLocations = [];
navigator.geolocation.getCurrentPosition(function (position) {
arrLocations.push(position.coords.latitude)
arrLocations.push(position.coords.longitude)
});
if (!arrLocations) {
resolve(arrLocations);
}
else {
reject();
}
})
.then(function (arr) {
return arr;
})
.catch(function (e) {
console.log(`Something went wrong: ${e}`);
});
Why is the element in the array returning undefined? And why is the promise returning undefined? Thanks!
getCurrentPosition()
is asynchronous, which is why your first snippet doesn't work. You are returning and trying to log arrLocations
before the async function has pushed anything. Using the promise in your second idea is a good intuition, it just needs a little tweaking.
Here's one way. Just resolve
the array you want and take advantage of getCurrentPosition
's second parameter for an error call back to reject if needed. (you'll probably just get the error in a SO snippet):
const getLocation = function() {
return new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(
(position) => resolve([position.coords.latitude, position.coords.longitude]),
(error) => reject(error)
);
})
}
// to use it:
getLocation()
.then(arrLocations => console.log(arrLocations))
.catch(err => console.log("there was an error: ", err))