Home > Net >  Returning the current precipitation value from an API in Java Script
Returning the current precipitation value from an API in Java Script

Time:12-17

So I have trouble with this list since I'm rather unfamiliar with js and api's. I have the following API, from which I wish to just get the value of the current hour:

https://api.open-meteo.com/v1/gfs?latitude=53.08&longitude=8.81&hourly=precipitation

Advice please?

API Documentation: https://open-meteo.com/en/docs/gfs-api#latitude=53.08&longitude=8.81&hourly=precipitation

Initiating a List and just getting the value of say "hour n" always returns 0.

CodePudding user response:

You could use fetch to call the API.

Once we have the result we could use Array.map() to create a list of precipitation objects from the hourly precipitation values.

Each precipitation object will look something like:

{ time: '2022-12-16T16:00' precipitation: 0.1 }

We can then add these values to a table for the week using document.createElement etc.

async function getPrecipitation() {
    const url = 'https://api.open-meteo.com/v1/gfs?latitude=53.08&longitude=8.81&hourly=precipitation';
    let result = await fetch(url).then(resp => resp.json());
    let precipitation = result.hourly.time.map((time, idx) => ({ time, precipitation: result.hourly.precipitation[idx]}));
    return precipitation;
}

function showPrecipationInTable(rows) {
    let el = document.getElementById('output');
    for(let row of rows) {
        let rowEl = document.createElement('tr');
        rowEl.innerHTML = `<td>${row.time}</td><td>${row.precipitation}</td>`;
        el.appendChild(rowEl)
    }
}

async function getAndShowPrecipitation() {
    let precipitation = await getPrecipitation();
    showPrecipationInTable(precipitation);
}

getAndShowPrecipitation()
 <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA 058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

 <table id="output" >
  <tr>
<th>Time</th>
<th>Precipitation</th>
  </tr>
</table> 

  • Related