DEV Community

Cover image for Using Weather API with JavaScript;
Areeb ur Rub
Areeb ur Rub

Posted on

Using Weather API with JavaScript;

Buy Me A Coffee

A simple weather app is something everyone should try making as it make us familiar with basics of API handling.

The Layout

So first what we have to create is a layout in which there will be a search box where city name can be entered and a card kind of thing where output can be shown.

The Card can contain City name, temperature, etc.. Will talk it about in API Section

Design the cards and input as per your creativity.

The API we are using

For this weather app we will be using OpenWeatherMap/API as it's free and easy to use.

To Start using it you should have an API key so first register yourself on this website and get the keys.

Click Here to get The API Key after signing up

Now Come to the JavaScript Part

  • First, bring all the DOM elements to JavaScript and add .onsubmit eventlistner to Form and get the text input value

  • Now we will create a function through which we will pass this city name and it will get the data from API and update the DOM

  • There are various methods to use API in JavaScript but we will be using the basic one the XMLHttpRequest();

  • using XHR in JS is simple just add


const xhr = new XMLHttpRequest();
xhr.open('GET',url);
xhr.send();
xhr.onload = () =>{
    // we can change the data type to json also by
    const data = JSON.prase(xhr.response);
    console.log(data);
};

this Handles API
in the place of url use https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=YOUR-TOKEN-GOES-HERE
this will return a object containing info of particular city.

  • First console.log(data); press Shift+Ctrl+J to check the console and observe the object
    image
    it give a lot of data, Now what we have to do is change DOM accordingly.

  • Use ELEMENT-SELETOR.innerHTML='THE-DATA' to Change the value in DOM

  • This API also returns a image for the weather and can be accessed from data.weather[0].icon it will give the icon name change the src of image to http://openweathermap.org/img/wn/${data.weather[0].icon}@2x.png
    To know more see the weather-icon docs

Check the pen to get more idea.

In this I have used OpenWeatherMap/Current API to get current data you can also explore other on OpenWeatherMap/API

Please use you API KEY don't burden my one too much as it's free to create one but have daily limits.


Read Also:


Follow me for more:

Buy Me A Coffee

Top comments (2)

Collapse
 
patzistar profile image
Patrick Schadler

Have you thought about using fetch instead of XMLHttpRequest? It is much more modern, but anyway, good work!

Collapse
 
areeburrub profile image
Areeb ur Rub

Yeah, I know about fetch( ) and Axios as well but I wanted to use XHR here.