Making a weather App using API and Glassmorphism

Photo by George Cox on Unsplash

Making a weather App using API and Glassmorphism

Making a weather app as a learner should be one of the best ways to practice your coding skills, and sometimes you ask yourself where to start from and what API to use to fetch the real-time weather data of a location for free. In this article, I will take you through how to create a beautiful weather app website that gives accurate, real-time weather information by accessing the location of the device using an open API. For this article, I am going to use the OpenWeatherMap to fetch my weather data.

Glassmorphism in CSS

What's an API? An API is a set of functions and procedures allowing the creation of applications that access the features or data of an operating system.

The div with the id #location, we will use to fetch the location of the device being accessed. The temperature of the day is loaded onto the div with class .weather reading both celsius and Fahrenheit, In case we are unable to fetch the data it will read error.

Fetching Weather data from API.

We will be using the OpenWeatherMap, You can subscribe to the free OpenWeatherMap and select the API key which you will use to retrieve real-time weather data, Select the free version.

JavaScript

We will create a var called API where we will store our API key, and create an Eventlistener that runs a function every time the page is loaded, to get the location, we will create two variables,

  • Longitude.

  • Latitude.

We will use the if statement to navigate and access the location of the user, and we will store the location coordinates in our variables longitude and latitude. With the coordinates safely stored in the variables, we can use them to query the OpenWeatherAPI, I have saved the link in the variable called link.

Let's look at the code snippet below.


window.addEventListener('load', () => {

  let longitude;

  let latitude;

  // Accesing Geolocation of User

  if (navigator.geolocation) {

    navigator.geolocation.getCurrentPosition((position) => {

      // Storing Longitude and Latitude in variables

      longitude = position.coords.longitude;

      latitude = position.coords.latitude;

      const link = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&appid=${api}&units=metric`;

Making an API call is the same as fetching data from the API using the link. Fortunately, since every API has a root endpoint, for OpenWeatherMap it is weather link and includes our location using ?, longitude, latitude coordinates, and the variable with the API key, so the link would look something like this weather link

In other words, the following is required during an API call.

  • Latitude and longitude parameters to get the geographical coordinates.

  • Appid, The personal API key generated.

  • mode, This is the response format. Ours is HTML, but OpenWeather also supports XML.

  • Units of measurement: We are using both Fahrenheit and Celsius.

  • Language. To get the output in the language we prefer, by default, we are using English.

We will use the URL and the fetch() javascript method object to retrieve the data from the API and return it to the App, A return .json() object translates the response into a JSON object, Then we will extract the data using the destructuring technique, In destructuring we create a variable with the name of an object's key that is wrapped in curly braces{} and assign to it the object.

Let's take a look at the code snippet below.


        fetch(link)

        .then((response) => {

          return response.json();

        })

        .then((data) => {

          const { temp } = data.main;

          const place = data.name;

          const { description, icon } = data.weather[0];

          const { sunrise, sunset } = data.sys;

          const iconUrl = `http://openweathermap.org/img/wn/${icon}@2x.png`;

          const fahrenheit = (temp * 9) / 5 + 32;

          // Converting Epoch(Unix) time to GMT

          const sunriseGMT = new Date(sunrise * 1000);

          const sunsetGMT = new Date(sunset * 1000);

We will use the fetch...then() statement to retrieve the temperature data, the location data, and the time of sunrise and sunset. Since we have included Fahrenheit in our coding, we will have to convert Celsius to Fahrenheit. We need to restrict the display to two decimal places, so we will use the toFixed() method to restrict the decimal places to 2. To get the local date and time, we use the toLocaleDateString() method and the toLocaleTimeString() method to convert GMT to local time.

Don't forget to work on accessing the DOM elements and changing the variables.

The entire code snippet is below.


// Openweathermap API. Do not share it with the public.

const api = '********************'; //Replace with your API

const iconImg = document.getElementById('weather-icon');

const loc = document.querySelector('#location');

const tempC = document.querySelector('.error');

const tempF = document.querySelector('.error2');

const desc = document.querySelector('.desc');

const sunriseDOM = document.querySelector('.sunrise');

const sunsetDOM = document.querySelector('.sunset');

window.addEventListener('load', () => {

  let longitude;

  let latitude;

  // Accesing Geolocation of User

  if (navigator.geolocation) {

    navigator.geolocation.getCurrentPosition((position) => {

      // Storing Longitude and Latitude in variables

      longitude = position.coords.longitude;

      latitude = position.coords.latitude;

      const link = `https://api.openweathermap.org/data/2.5/weather?latitude=${lat}&longitude=${long}&appid=${api}&units=metric`;

      // Using fetch to get data

      fetch(link)

        .then((response) => {

          return response.json();

        })

        .then((data) => {

          const { temp } = data.main;

          const place = data.name;

          const { description, icon } = data.weather[0];

          const { sunrise, sunset } = data.sys;

          const iconUrl = `http://openweathermap.org/img/wn/${icon}@2x.png`;

          const fahrenheit = (temp * 9) / 5 + 32;

          // Converting Epoch(Unix) time to EAT

          const sunriseGMT = new Date(sunrise * 1000);

          const sunsetGMT = new Date(sunset * 1000);

          // Interacting with DOM to show data

          iconImg.src = iconUrl;

          loc.textContent = `${place}`;

          desc.textContent = `${description}`;

          tempC.textContent = `${temp.toFixed(2)} °C`;

          tempF.textContent = `${fahrenheit.toFixed(2)} °F`;

          sunriseDOM.textContent = `${sunriseGMT.toLocaleDateString()}, ${sunriseGMT.toLocaleTimeString()}`;

          sunsetDOM.textContent = `${sunsetGMT.toLocaleDateString()}, ${sunsetGMT.toLocaleTimeString()}`;

        });

    });

  }

Glassmorphism.

Glassmorphism is majorly created based on the backdrop-filter CSS property set to blur, In our case, we will set the value to blur2.6px. In order for the writings to be visible, we will set the opacity property to 50% of the blur value and our words will be visible. Let's look at the code snippet below.


.glass{/* creating CSS glassmorphism */

background: rgba(242, 237, 237, 0.18);

border-radius: 16px;

box-shadow: 0 4px 30px rgba(0, 0, 0, 0.1);

backdrop-filter: blur(2.6px);

-webkit-backdrop-filter: blur(10px);

border: 1px solid rgba(242, 237, 237, 0.77);

opacity: 50%;

height: 550px;

width: 400px;

border-radius: 10px;

position: center;

margin-left: 500px;

margin-top: -360px;

There you have it, You have created your own personal working weather app using an API and glassmorphism.

Resources. openweathermap.org

#javascript