使用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
相关产品推荐
相关产品推荐

