Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
439 views
in Technique[技术] by (71.8m points)

javascript - Openweather.com API 5 next days forecast issue

this is my first time using openweather.com API for weather forecasts, I just want to show the following information for the next 5 days:

Min and Max temperature of each day Weather icon Current weather description (Drizzle, Sunny...)

Plain simple, for some reason I'm getting pretty weird results, take a look at the image bellow so you can understand (I THINK that this five results are actually of the same day, different timestamps, look at min/max temp, maybe? instead of the next 5 days...

enter image description here

This is my code:

async getForecast()
    {
        let url = "https://api.openweathermap.org/data/2.5/forecast";
        let payload = 
        {
            lat: this.$app.globals.origin.lat,
            lon: this.$app.globals.origin.lng,
            units: 'metric',
            APPID: '0feb06072d87320932559f321ca221fb',
            lang:'es',
            cnt:5
        };

        let response = await axios.get(url, { params: payload });
        this.data = response.data.list;
    }

In my view (Vue.js):

<div style="width:auto; height:100%; display:flex; align-items:center;">
                <a  style="width:auto; padding:10; height:100%; display:flex; flex-direction:column; align-items:center; justify-content:space-around;" v-for="(item,index) in data" :key="index">
                    <span class="fs_smaller c_normal">{{ item.main.temp_min }} / {{ item.main.temp_max }}</span>
                    <span class="fs_smaller c_normal">{{ item.weather[0].description }}</span>
                    <img style="width:50px; height:auto;" :src="'https://openweathermap.org/img/w/'+item.weather[0].icon+'.png'">
                </a>
            </div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The API endpoint you're hitting is the 3-hour-forecast for the next 5 days:
https://openweathermap.org/forecast5

If you inspect the response, you'll see a dt_txt property in the list items. There you can see that the items are 3 hours apart.

You could use the daily forecast, which has the same API schema, it just adds a /daily to the URL:
https://openweathermap.org/forecast16

You could extract the values like this:

import _ from "lodash"
const itemsByDay = _.groupBy(response.list, item => item.dt_txt.slice(0, 10))
const extrema = _.mapValues(itemsByDay, items => ({
    min: _.min(_.map(items, 'main.temp_min')),
    max: _.max(_.map(items, 'main.temp_max')),
}))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...