2017-09-28 5 views
0

私はFCCプロジェクトのjavascriptを使用して天気予報アプリを表示しようとしています。現在の天気を最初に表示するために、私は装置の位置を見つけなければなりません。これはうまくHTML geolocationを使用して動作します。しかし、緯度と経度は、グローバル変数に割り当てようとしていますが、関数eventhoughの外でそれを使用しようとすると、私にundefinedエラーを出しています。経度APIからデータを取得しようとしているときに未定義

$(document).ready(function(){ 
     var lon; 
     var lat; 
     function getLocation(){ 
     if(navigator.geolocation){ 
      navigator.geolocation.getCurrentPosition(showPosition); 
     } 
     else{ 
      console.log("your device is not suported!"); 
     }} 

     function showPosition(position){ 
     var pos = position.coords 
     lat = pos.latitude; 
     lon = pos.longitude; 

     } 
     console.log(lat); // for debugging, here is the undefined error 
     $.ajax({ 
     type: 'GET', 
     url: 'https://fcc-weather-api.glitch.me/api/current?lat=35&lon=139', 
     success: function(data){ 
      $('h1').html("<strong>" + data.coord.lat + "</strong>"); 
      console.log(latitude); 
     }, 
     error: function(error){ 
      console.log(error); 
     } 

     }); 
     }); 

助けてくれてありがとう:)

+0

コードに未定義の「緯度」があります。 Ajaxの成功関数の 'console.log(latitude);を参照してください。 これを 'data.coord.lat'に変更することもできます(上記の行のように)。 – JonahAaron

+0

これを確認してください:https://stackoverflow.com/questions/9935059/saving-variables-outside-of-navigator-geolocation-getcurrentposition-javascrip – ErisoHV

答えて

1

は、位置を取得するブラウザは、ユーザからの承認を得る必要があるため、非同期に行われます。そのため、Webサービスを呼び出す必要があります。

$(document).ready(function(){ 
    var lon; 
    var lat; 
    function getLocation(){ 
    if(navigator.geolocation){ 
     navigator.geolocation.getCurrentPosition(showPosition); 
    } 
    else{ 
     console.log("your device is not suported!"); 
    }} 

    function showPosition(position){ 
    var pos = position.coords 
    lat = pos.latitude; 
    lon = pos.longitude; 


    console.log(lat); // should not be undefined anymore. 
    $.ajax({ 
     type: 'GET', 
     url: 'https://fcc-weather-api.glitch.me/api/current?lat=' + lat + '&lon=' + lon, 
     success: function(data){ 
     $('h1').html("<strong>" + data.coord.lat + "</strong>"); 
     console.log(latitude); 
     }, 
     error: function(error){ 
     console.log(error); 
     } 

    }); 
    } 
}); 
0

まあ、showPositionとgetLocationを宣言するだけです。 実際にはshowPosition()のように呼び出さないので、latとlonは未定義のままです

関連する問題