JavaScript: how to use the Open Weather Map API

JavaScript: how to use the Open Weather Map API

We can get the meteo information about a place with JavaScript using thee Open Weather Map API.

We can get the meteo information about a place with JavaScript using thee Open Weather Map API.

We can use the Fetch API to get the results from the API in JSON format. The q parameter represents the name of the place whereas appid is our API key.

The remote API allows CORS so we can directly access the endpoint via JavaScript without the need of a server side proxy. Once we get the results, we display the returned JSON string on the page.


'use strict';

const API_KEY = 'Your API key';

const request = async url => {
    const reponse = await fetch(url);
    return response.ok ? response.json() : Promise.reject({error: 500});
};

const getWeatherInfo = async ( element, form ) => {
    try {
        const q = form.querySelector('#q').value;
        const url = `https://api.openweathermap.org/data/2.5/weather?q=${q}&appid=${API_KEY}`;
        const response = await request(url);
        element.innerText = JSON.stringify(response);

    } catch(err) {
        console.log(err);
    }
};

document.addEventListener('DOMContentLoaded', () => {
    const form = document.querySelector('#form');
    form.addEventListener('submit', e => {
        e.preventDefault();
        getWeatherInfo(document.querySelector('#results'), form);
    }, false);
});

You can see the above code in action on the following page.