Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 30, 2021 05:28 pm GMT

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:
.ltag__user__id__417828 .follow-action-button { background-color: #000000 !important; color: #ffffff !important; border-color: #000000 !important; }
areeburrub image

Buy Me A Coffee


Original Link: https://dev.to/areeburrub/using-weather-api-with-javascript-3a04

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To