DEV Community

Cover image for Consulting Temperature API with JS
Walter Nascimento
Walter Nascimento

Posted on

Consulting Temperature API with JS

[Clique aqui para ler em português]

Let’s make a query for a temperature api using javascript fetch

Code

First let’s create the interface, we’ll do something simple, using just HTML.

<div>
  <span id="city"></span>
  <span id="temperature"></span>
</div>
Enter fullscreen mode Exit fullscreen mode

To present the data we have a div with two spans, one to represent the city and the other to represent the temperature.

const CITY = document.getElementById('city');
const TEMPERATURE = document.getElementById('temperature');
const URL_MAIN = 'https://api.openweathermap.org/data/2.5/weather';
const API_KEY = '8f57cb746c4c1d4b48b7f35eba6f6230';
const UNITS = 'metric';

navigator.geolocation.getCurrentPosition(loadUrl);

function loadUrl(pos) {
  let lat = pos.coords.latitude;
  let long = pos.coords.longitude;
  let url = `${URL_MAIN}?lat=${lat}&lon=${long}&units=${UNITS}&APPID=${API_KEY}`;
  fetchApi(url);
};

async function fetchApi(url) {
  let response = await fetch(url);
  let { main, name } = await response.json();
  let temperature = (main.temp).toFixed(1);
  CITY.innerText = `${name}:`;
  TEMPERATURE.innerText = `${temperature} ºC`;
}
Enter fullscreen mode Exit fullscreen mode

First of all you need to be registered on the openweathermap site, when you register you will have access to the key so just change the parameters in the js code.

In the constants we have city, a constant with the span city element and one with the span temperature element, then we have three support constants for the query, URL_MAIN (where the url of the openweathermap site is), API_KEY (where the access key is) and UNITS (where is the type of unit that will be returned from the api, for more information see the website).

To start, the browser’s own geolocation api is called, and with it the loadUrl function is called.

In the loadUrl function we get the coordinate that came from the geolocation api and we set the url to consult the api.

In the fetchApi function a query is made for the url that was created and when we have the api response it is displayed on the page with the innerText.

ready simple like that.

Demo

See below for the complete working project.

if you can't see it click here and see the final result

Youtube

If you prefer to watch it, see the development on youtube.


Thanks for reading!

If you have any questions, complaints or tips, you can leave them here in the comments. I will be happy to answer!

😊😊 See you later! 😊😊


Support Me

Youtube - WalterNascimentoBarroso
Github - WalterNascimentoBarroso
Codepen - WalterNascimentoBarroso

Top comments (0)