I am using getCurrentPosition to get local latitude and longitude. I know this function is asynchronous, just wondering how to return latitude and longitude value that can be accessed by other functions?
function getGeo() {
navigator.geolocation.getCurrentPosition(getCurrentLoc)
}
function getCurrentLoc(data) {
var lat,lon;
lat=data.coords.latitude;
lon=data.coords.longitude;
getLocalWeather(lat,lon)
initMap(lat,lon)
}
I am using getCurrentPosition to get local latitude and longitude. I know this function is asynchronous, just wondering how to return latitude and longitude value that can be accessed by other functions?
function getGeo() {
navigator.geolocation.getCurrentPosition(getCurrentLoc)
}
function getCurrentLoc(data) {
var lat,lon;
lat=data.coords.latitude;
lon=data.coords.longitude;
getLocalWeather(lat,lon)
initMap(lat,lon)
}
Share
Improve this question
edited Apr 15, 2019 at 6:57
Dale K
27.3k15 gold badges57 silver badges83 bronze badges
asked Nov 29, 2017 at 3:27
heihei
1091 gold badge2 silver badges10 bronze badges
1 Answer
Reset to default 18I would suggest you wrapping it in a promise:
function getPosition() {
// Simple wrapper
return new Promise((res, rej) => {
navigator.geolocation.getCurrentPosition(res, rej);
});
}
async function main() {
var position = await getPosition(); // wait for getPosition to plete
console.log(position);
}
main();
https://jsfiddle/DerekL/zr8L57sL/
ES6 version:
function getPosition() {
// Simple wrapper
return new Promise((res, rej) => {
navigator.geolocation.getCurrentPosition(res, rej);
});
}
function main() {
getPosition().then(console.log); // wait for getPosition to plete
}
main();
https://jsfiddle/DerekL/90129LoL/