【问题标题】:Longitude Undefined while trying to retrieve a data from an API尝试从 API 检索数据时未定义经度
【发布时间】:2017-09-28 20:23:08
【问题描述】:

我正在尝试使用 FCC 项目中的 javascript 制作一个天气显示应用程序。为了首先显示当前天气,我必须找到设备的位置。使用 HTML 地理位置可以正常工作。但是当我尝试在函数外部使用它时,纬度和经度给了我undefined 错误,即使我试图将它分配给全局变量。

$(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);
        }

        });
      });

感谢您的帮助:)

【问题讨论】:

  • 您的代码中有一个未定义的“纬度”。请参阅 Ajax 的成功函数中的 console.log(latitude);。也许将其更改为data.coord.lat(如上一行)。

标签: javascript jquery ajax


【解决方案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);
       }

    });
  }
});

【讨论】:

    【解决方案2】:

    好吧,你只需声明 showPosition 和 getLocation 。 你不会真的像 showPosition() 这样称呼它们,所以 lat 和 lon 保持未定义

    【讨论】:

      猜你喜欢
      • 2016-12-17
      • 1970-01-01
      • 1970-01-01
      • 2022-01-20
      • 1970-01-01
      • 2019-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多