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

OpenWeatherMap OneCall 2.5接口历史降水数据获取问题咨询

OpenWeatherMap OneCall 2.5 Timemachine接口降水数据获取方案

接口是否提供降水数据?

是的,OneCall 2.5的timemachine接口支持返回降水数据,但仅当目标时间点/时间段存在降水记录时才会显示对应字段,且默认请求不会强制返回(无降水时字段不出现)。

如何获取降水数据?

1. 降水字段的位置

降水相关字段分为两种场景:

  • current数据块:对应请求dt参数指定的时刻,若该时刻有降水,会返回rain或snow对象,包含1h字段(过去1小时的降水量,单位随units参数变化:imperial为英寸,metric为毫米)。
  • hourly数据块:包含目标日期当天逐小时的气象数据,每个小时条目里同样会有rain/snow对象,适合获取全天降水分布或总和。

2. 修改请求与代码

你的当前请求已包含必要参数(无需额外添加特殊参数,只要不通过exclude排除current或hourly块即可),但需要在代码中处理可能存在的降水字段:

修改后的代码示例

const API_KEY = "XXX";
const LATITUDE = 26.640629;
const LONGITUDE = -81.872307;

const endDate = new Date();
const startDate = new Date(endDate.getTime() - (5 * 24 * 60 * 60 * 1000));

async function getWeatherData() {
  try {
    const weatherDataList = [];
    for (let date = startDate; date <= endDate; date.setDate(date.getDate() + 1)) {
      const weatherData = await (await fetch(`https://api.openweathermap.org/data/2.5/onecall/timemachine?lat=${LATITUDE}&lon=${LONGITUDE}&dt=${Math.floor(date.getTime() / 1000)}&appid=${API_KEY}&units=imperial`)).json();

      const weatherDataLocalList = [];

      // 原有基础气象数据
      weatherDataLocalList.push(weatherData.current.temp);
      weatherDataLocalList.push(weatherData.current.humidity);
      weatherDataLocalList.push(weatherData.current.pressure * 0.02952998751);
      weatherDataLocalList.push(weatherData.current.wind_speed * 0.44704);
      
      // 获取当前时刻总降水量(无降水时返回0)
      const currentRain = weatherData.current.rain?.['1h'] || 0;
      const currentSnow = weatherData.current.snow?.['1h'] || 0;
      weatherDataLocalList.push(currentRain + currentSnow);

      // 可选:获取当天逐小时降水总和(按需添加)
      let dailyTotalPrecip = 0;
      if (weatherData.hourly) {
        weatherData.hourly.forEach(hour => {
          dailyTotalPrecip += hour.rain?.['1h'] || 0;
          dailyTotalPrecip += hour.snow?.['1h'] || 0;
        });
        // weatherDataLocalList.push(dailyTotalPrecip);
      }

      weatherDataList.push(weatherDataLocalList);
    }
    predict2(weatherDataList);
  } catch (error) {
    console.error("Error fetching weather data:", error);
  }
}

getWeatherData();

关键注意点

  • 降水字段仅在有降水记录时存在,必须用可选链(?.)或条件判断避免无字段时的报错。
  • Timemachine接口仅支持最近5天的历史数据,你的代码逻辑符合该限制。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 01:15:35