【问题标题】:How to get min and max temp for the day, from 5 day weather forecast JS?如何从 5 天天气预报 JS 中获取当天的最低和最高温度?
【发布时间】:2019-08-08 20:45:18
【问题描述】:

我正在构建需要显示 5 天天气预报的 Web 应用程序。我从https://openweathermap.org/forecast5 获取数据我的想法是使用来自 api 的数据通过数组的 8 个索引来放置每天的信息。请原谅我的英语不好,这里是截图以便更好地理解 - https://imgur.com/a/4RHjZ5g 这是 API 示例 - https://samples.openweathermap.org/data/2.5/forecast?q=M%C3%BCnchen,DE&appid=b6907d289e10d714a6e88b30761fae22

从屏幕截图中可以看出,索引 0 获取最近 3 小时循环(12、15、16 等)的天气数据。在几乎每一种情况下,我都会获得每天的数据。

我不明白如何获取每天的最小值和最大值。如果今天的数据是从索引 0 的 15:00 开始的,那么在此之前我无法获取信息。我只能在 15:00 到 00:00 点之间获得温度。

第一天我从 API 获得了这些信息:

.list[0].dt_txt
.list[0].main.temp
.list[0].weather[0].description

对于第二个 8,对于第三个 16 等等......

【问题讨论】:

  • 我会使用每日预报 API,因为它已经包含每天的最低和最高温度
  • 这是我脑海中的下一个想法......

标签: javascript api weather


【解决方案1】:

如前所述,使用history API。要获取慕尼黑今天 + 未来 4 天的值,请使用以下内容:

const getStartAndEndDateTimestamps = increment => {
    let startDate = new Date();
    startDate.setDate(startDate.getDate() + increment);
    startDate.setHours(0,0,0,0);
    let endDate = new Date();
    endDate.setDate(endDate.getDate() + increment);
    endDate.setHours(23,59,59,999);
    return {
        start: startDate.valueOf(),
        end: endDate.valueOf()
    };
};

const city = 'München';

[0, 1, 2, 3, 4].forEach(increment => {
    const timestamps = getStartAndEndDateTimestamps(increment);
    const requestUrl = `http://history.openweathermap.org/data/2.5/history/city?q=${encodeURIComponent(city)}&type=hour&start=${timestamps.start}&end=${timestamps.end}`;
    // get & process API data
});

【讨论】:

    【解决方案2】:

    也许您可以使用API 的历史版本。 也许其他选项可能是为历史值创建服务器端 cookie 或小型数据库。

    【讨论】:

    • 嗯坦克我去看看。
    【解决方案3】:

    根据从给定 API 获得的响应

    let weather=" assign response got from API to here";
    
    let minArray=[];
    let maxArray=[];  
    for (let i of weather.list)  
     {  minArray.push(Number( i.main.temp_min)) ; 
        maxArray.push(Number(i.main.temp_max));  }
      console.log("min temp is "+ Math.min(...minArray));
     console.log("max temp is "+ Math.max(...maxArray));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-30
      • 1970-01-01
      • 2019-06-10
      • 2020-08-29
      • 2013-02-28
      • 2021-05-01
      • 2016-01-27
      相关资源
      最近更新 更多