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

如何在JavaScript中从Open-Meteo API获取当前小时降水量值?

解决Open-Meteo API获取降水量始终返回0的问题

常见原因及解决方案

1. 时间索引匹配错误(最可能)

Open-Meteo API返回的hourly.time数组是UTC时间序列,而非本地时间。如果用本地时间计算的"第n小时"去匹配索引,大概率会对应到无降水的时间点,导致返回0。

2. 未正确解析API数据结构

API返回的降水数据hourly.precipitation与hourly.time是严格一一对应的数组,必须确保索引完全匹配。

可行代码示例(原生JavaScript)

// 请求Open-Meteo降水数据
fetch('https://api.open-meteo.com/v1/gfs?latitude=53.08&longitude=8.81&hourly=precipitation')
  .then(res => res.json())
  .then(data => {
    const timeArr = data.hourly.time;
    const precipArr = data.hourly.precipitation;

    // 方法1:获取当前UTC小时的降水量
    const nowUTC = new Date();
    const currentUTCHour = nowUTC.toISOString().slice(0, 13) + ':00';
    const currentIndex = timeArr.indexOf(currentUTCHour);

    if (currentIndex !== -1) {
      console.log(`当前UTC小时降水: ${precipArr[currentIndex]}mm`);
    } else {
      console.log('未找到对应UTC时间的降水数据');
    }

    // 方法2:获取指定第n小时的数据(索引从0开始,比如第3小时填n=2)
    const targetHourIndex = 2;
    if (targetHourIndex < precipArr.length) {
      console.log(`第${targetHourIndex+1}小时(${timeArr[targetHourIndex]})降水: ${precipArr[targetHourIndex]}mm`);
    } else {
      console.log('指定小时超出API返回的时间范围');
    }

    // 排查用:打印所有小时数据,直观检查降水值
    console.log('所有小时降水数据:', data.hourly);
  })
  .catch(err => console.error('请求失败:', err));

关键排查步骤

  • 直接在浏览器打开API链接,查看返回的JSON,确认hourly.precipitation数组中是否存在非0值。如果全为0,说明该区域在API覆盖时段内确实无降水。
  • 检查你要获取的"第n小时"对应的时间字符串,是否存在于hourly.time数组中,用indexOf方法确认索引有效性,避免因时区或计算错误选到错误位置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 09:01:15