调用OpenWeatherMap API无法获取当前位置温度问题求助
问题排查与解决方案
核心问题1:API服务商不匹配
你订阅的是OpenWeatherMap,但代码里调用的是weatherapi.com的接口——这是两个完全独立的天气服务提供商,接口规则、参数格式、返回数据结构都不兼容,直接导致无法获取数据。
修正方案:
替换为OpenWeatherMap的官方接口,同时调整参数和数据解析逻辑,并且通过浏览器API获取真实地理位置:
window.addEventListener('load', () => { // 利用浏览器地理位置API获取当前经纬度(已开启权限可正常调用) navigator.geolocation.getCurrentPosition(position => { const latitude = position.coords.latitude; const longitude = position.coords.longitude; const apiKey = '你的OpenWeatherMap API密钥'; // 替换为实际密钥 // OpenWeatherMap 当前天气接口的正确格式 const apiUrl = `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&units=metric&appid=${apiKey}`; fetch(apiUrl) .then(response => { if (!response.ok) { throw new Error(`请求失败:${response.statusText}`); } return response.json(); }) .then(data => { const temperature = data.main.temp; // OpenWeatherMap的温度字段位于main对象下 console.log(`当前温度: ${temperature}°C`); }) .catch(error => { console.error('获取天气数据失败:', error); }); }, error => { console.error('获取位置信息失败:', error); }); });
核心问题2:位置信息未正确获取
你代码中的latitude和longitude是硬编码的占位符pastenumber,没有实际调用浏览器的地理位置API获取真实经纬度——即使开启了权限,也需要主动触发位置获取逻辑。
关于net::ERR_INTERNET_DISCONNECTED错误
该错误表明当前环境(服务器或浏览器)无法连接到OpenWeatherMap的API服务器,需检查:
- 部署代码的服务器是否具备外网访问权限
- 浏览器端网络连接是否正常
- 可直接在浏览器地址栏输入替换好参数的API链接,测试是否能返回正常JSON数据
额外注意事项
- 确认API密钥正确,且未超出OpenWeatherMap免费版的调用次数限制
- 跨域问题:本地开发(localhost)默认允许跨域;正式域名部署时,OpenWeatherMap的公开API已支持跨域请求,无需额外配置
内容的提问来源于stack exchange,提问作者cythan
相关产品推荐
相关产品推荐

