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

使用Geolocation获取经纬度调用OpenWeather API失败该如何解决?

代码问题排查及修复

存在的核心问题

  • 异步执行逻辑错误:navigator.geolocation.getCurrentPosition是异步接口,触发回调前latUser、lonUser均为空值,此时调用天气接口会出现参数错误
  • 请求URL缺少协议头:没有加https://前缀,浏览器会按相对路径发起请求,无法命中OpenWeather的服务地址
  • 返回值解析错误:OpenWeather返回的weather字段是数组类型,需要取下标0的元素才能获取天气描述字段
  • 未主动触发接口调用:仅定义了fetchWeather方法,没有对应的执行逻辑
  • (可选优化)默认返回的温度单位为开尔文,可新增units=metric参数直接获取摄氏度数值

修复后可运行代码

/*Geolocation*/
let latUser, lonUser;

const errorCallback = (error) => {console.error('定位失败:', error)}
const successCallback = (position) => {
    // 定位成功后再调用天气查询接口
    latUser = position.coords.latitude
    lonUser = position.coords.longitude
    weather.fetchWeather()
}

navigator.geolocation.getCurrentPosition(successCallback, errorCallback) 

/*Weather*/
let weather = {
    "apiKey": "替换为你实际的OpenWeather API密钥",
    fetchWeather: function () {
        // 补全协议头,新增单位参数
        fetch(`https://api.openweathermap.org/data/2.5/weather?lat=${latUser}&lon=${lonUser}&appid=${this.apiKey}&units=metric`)
        .then((response) => {
            if(!response.ok) throw new Error('接口请求失败,状态码:' + response.status)
            return response.json()
        })
        .then((data) => this.displayWeather(data))
        .catch(err => console.error('天气查询出错:', err))
    },
    displayWeather: function(data){
        const { temp, humidity } = data.main
        // 取weather数组第一个元素的描述
        const { description } = data.weather[0]
        console.log('温度:' + temp + '℃,湿度:' + humidity + '%,天气:' + description)
    }
}

内容的提问来源于stack exchange,提问作者veréb

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 16:15:04