2017-07-29 4 views
-1

私はjavascriptを使い慣れていて、ユーザーの地域に温度を表示するウェブサイトを構築しようとしていますが、lalg変数はshowPosition()関数の外では定義されていません。天気を取る。なぜ私の変数は自分の関数の外で定義されていませんか?

はここで完全なコードです:

var la; 
var lg; 

function getLocation() { 
if (navigator.geolocation) 
    navigator.geolocation.getCurrentPosition(showPosition); 
} 

function showPosition(position) { 
la= position.coords.latitude; 
lg= position.coords.longitude; 
} 

getLocation(); 

var url="https://fcc-weather-api.glitch.me/api/current?lat=" + la + "&lon=" + lg; 
document.getElementById("im").innerHTML="Latitude:" + la; 

fetch(url) 
.then((resp) => resp.json()) 
.then(function(data) { 
    document.getElementById("temper").innerHTML="Temperature:" + data.main.temp; 
}) 
.catch(function(error) { 
    console.log("error: " + error); 
}); 

私はlalg変数がdocument.getElementById("im").innerHTML="Latitude:" + laラインと正しいかどうかをテストすることを決めたが、私はLatitude:undefinedを取得します。私はshowPosition()関数内で同じテストを行い、変数が正しく定義されています。これをどうすれば解決できますか?

答えて

0

showPositionがすぐに呼び出されないという問題があります(たとえば、GPSの初期化に時間がかかるなど)。したがって、あなたがあなたの位置データを受信するまで、あなたの要求を待たなければならない:

var la; 
var lg; 

function getLocation() { 
if (navigator.geolocation) 
    navigator.geolocation.getCurrentPosition(showPosition); 
} 

function showPosition(position) { 
la = position.coords.latitude; 
lg = position.coords.longitude; 

var url="https://fcc-weather-api.glitch.me/api/current?lat=" + la + "&lon=" + lg; 
document.getElementById("im").innerHTML="Latitude:" + la; 

fetch(url) 
    .then((resp) => resp.json()) 
    .then(function(data) { 
    document.getElementById("temper").innerHTML="Temperature:" + data.main.temp; 
    }) 
    .catch(function(error) { 
    console.log("error: " + error); 
    }); 
} 

getLocation(); 
0

使用をこの:

function getLocation() { 
    if (navigator.geolocation) 
     navigator.geolocation.getCurrentPosition(showPosition); 
} 

function showPosition(position) { 
    var la= position.coords.latitude; 
    var lg= position.coords.longitude; 
    fetchTemperature(la, lg); // create a method for fetch temperature and send la and lg to it 
} 

function fetchTemperature(la, lg){ // method for fetch temperature 
    var url="https://fcc-weather-api.glitch.me/api/current?lat=" + la + "&lon=" + lg; 
    document.getElementById("im").innerHTML="Latitude:" + la; 

    fetch(url) 
    .then((resp) => resp.json()) 
    .then(function(data) { 
     document.getElementById("temper").innerHTML="Temperature:" + data.main.temp; 
    }) 
    .catch(function(error) { 
     console.log("error: " + error); 
    }); 
} 

getLocation(); 
+0

はお時間をいただき、ありがとうございます!私はそれを試みます。 – Daniel

関連する問題