本文介紹了geolocation.getCurrentPosition 如何返回值?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我正在使用 getCurrentPosition 來獲取當地的緯度和經度.我知道這個函數是異步的,只是想知道如何返回其他函數可以訪問的經緯度值?
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 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 complete
console.log(position);
}
main();
https://jsfiddle.net/DerekL/zr8L57sL/
ES6 版本:
function getPosition() {
// Simple wrapper
return new Promise((res, rej) => {
navigator.geolocation.getCurrentPosition(res, rej);
});
}
function main() {
getPosition().then(console.log); // wait for getPosition to complete
}
main();
https://jsfiddle.net/DerekL/90129LoL/
這篇關于geolocation.getCurrentPosition 如何返回值?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯(lián)網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯(lián)系我們刪除處理,感謝您的支持!