2017-11-29 9 views
0

私は地元の緯度と経度を取得するためにgetCurrentPositionを使用しています。この関数は非同期で、他の関数からアクセスできる緯度と経度の値を返す方法は不思議ですね。 ありがとう!geolocation.getCurrentPositionはどのように戻り値を返しますか?

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) 
    } 

答えて

0

は、あなたは他の機能がアクセスできるように、グローバルlat,lonを宣言しなければなりません。

var lat,lon; /* Declare it here */ 

function getGeo() { 
    navigator.geolocation.getCurrentPosition(getCurrentLoc) 
} 

function getCurrentLoc(data) { 
    lat=data.coords.latitude; 
    lon=data.coords.longitude; 
    getLocalWeather(lat,lon) 
    initMap(lat,lon) 
} 

jsFiddle:https://jsfiddle.net/pLu5z1bg/1/

+0

こんにちは、グローバル変数として宣言するとlatとlonは未定義です – hei

+0

'getCurrentLoc'の宣言(' var lat、lon')を削除しましたか? – Eddie

+0

しました。これらの2つの値を返すことはできますか? – hei

1
私はあなたが約束でそれを包むことをお勧め

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/

関連する問題