You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用经纬度参数调用getJSON接口时脚本无法正常运行

解决经纬度变量无法传入getJSON请求的问题

嘿,你这是踩了异步操作的典型坑啦!问题出在地理定位API是异步执行的——navigator.geolocation.getCurrentPosition不会立刻返回位置数据,它会等浏览器获取到用户位置后,才会调用你写的回调函数。但你现在把$.getJSON放在了回调函数外面,这时候latitude和longitude还没被赋值呢,甚至可能根本不存在,所以请求URL里的变量是空的,自然没法正常运行。

修正方案:把getJSON放到回调函数内部

要确保只有在拿到经纬度之后再发起请求,直接把$.getJSON的调用移到getCurrentPosition的回调里就行,这样就能顺利用上刚获取到的位置变量了。修正后的代码如下:

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(function(position) {
    // 成功获取到位置,赋值变量
    var latitude = position.coords.latitude;
    var longitude = position.coords.longitude;
    
    // 在这里发起getJSON请求,确保变量已赋值
    $.getJSON(`https://fcc-weather-api.glitch.me/api/current?lat=${latitude}&lon=${longitude}`, function(weatherData) {
      // 这里可以处理返回的天气数据,比如渲染到页面上
      console.log("获取到的天气数据:", weatherData);
    });
  });
} else {
  // 处理浏览器不支持地理定位的情况
  alert("哎呀,你的浏览器不支持地理定位功能,没法获取天气哦");
}

额外优化:加上错误处理

为了让应用更健壮,最好加上获取位置失败的处理逻辑,比如用户拒绝授权、位置获取超时等情况,给用户友好的提示:

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(
    // 成功获取位置的回调
    function(position) {
      var latitude = position.coords.latitude;
      var longitude = position.coords.longitude;
      
      $.getJSON(`https://fcc-weather-api.glitch.me/api/current?lat=${latitude}&lon=${longitude}`, function(weatherData) {
        console.log("天气数据:", weatherData);
      });
    },
    // 获取位置失败的回调
    function(error) {
      switch(error.code) {
        case error.PERMISSION_DENIED:
          alert("你拒绝了位置授权,无法获取天气信息哦");
          break;
        case error.POSITION_UNAVAILABLE:
          alert("暂时无法获取你的位置,请稍后再试");
          break;
        case error.TIMEOUT:
          alert("获取位置超时啦,再试一次吧");
          break;
        default:
          alert("获取位置时出了点小问题,请重试");
      }
    }
  );
} else {
  alert("你的浏览器不支持地理定位功能");
}

关键知识点回顾

  • 异步操作顺序:像地理定位、AJAX这类异步操作,不会按代码顺序立刻执行结果,必须等待操作完成后通过回调函数处理后续逻辑。
  • 变量作用域:回调函数内部定义的latitude和longitude是局部变量,外面的代码访问不到,所以必须在回调内部使用这些变量。

内容的提问来源于stack exchange,提问作者ondrejm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:57:35