Realtime Weather Forecast App using JavaScript - Coding Torque

Realtime Weather Forecast App using JavaScript - Coding Torque

Realtime Weather Forecast App

Hello Guys! Welcome to Coding Torque. In this blog, I'm going to explain to you how to make a Realtime Weather Forecasting app using javascript. You can extend this app to the next level by adding more functionalities like past and future days forecast. This will be a step-by-step guide. Let's get started 🚀.

Let's go step by step:

Step 1: HTML Code


<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Weather Web App</title>
  <link rel="preconnect" href="https://fonts.gstatic.com">
  <link href="https://fonts.googleapis.com/css2?family=Open+Sans&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="./src/styles.css">
  <script src="./src/script.js" defer></script>
</head>
<body>
  <!--Weather Card-->
  <div class="card">
    <div class="search">
      <input type="text" class="search-bar" placeholder="Search">
      <button><svg stroke="currentColor" fill="currentColor" stroke-width="0" viewBox="0 0 1024 1024" height="1.5em"
          width="1.5em" xmlns="http://www.w3.org/2000/svg">
          <path
            d="M909.6 854.5L649.9 594.8C690.2 542.7 712 479 712 412c0-80.2-31.3-155.4-87.9-212.1-56.6-56.7-132-87.9-212.1-87.9s-155.5 31.3-212.1 87.9C143.2 256.5 112 331.8 112 412c0 80.1 31.3 155.5 87.9 212.1C256.5 680.8 331.8 712 412 712c67 0 130.6-21.8 182.7-62l259.7 259.6a8.2 8.2 0 0 0 11.6 0l43.6-43.5a8.2 8.2 0 0 0 0-11.6zM570.4 570.4C528 612.7 471.8 636 412 636s-116-23.3-158.4-65.6C211.3 528 188 471.8 188 412s23.3-116.1 65.6-158.4C296 211.3 352.2 188 412 188s116.1 23.2 158.4 65.6S636 352.2 636 412s-23.3 116.1-65.6 158.4z">
          </path>
        </svg></button>
    </div>
    <div class="weather loading">
      <h2 class="city">Weather in Manipal</h2>
      <h1 class="temp">25.02°C</h1>
      <div class="flex">
        <img src="https://openweathermap.org/img/wn/04n.png" alt="" class="icon" />
        <div class="description">Cloudy</div>
      </div>
      <div class="humidity">Humidity: 91%</div>
      <div class="wind">Wind speed: 63.05 km/h</div>
    </div>
    <a target="_blank" rel="noopener noreferrer" href="https://github.com/VarunBanka">
      <img alt="github" src="./images/1632512_circle_github_round icon_icon.png" width="70" height="70"></a>
  </div>
  <!--Vanilla tilt.js Library Refer- https://micku7zu.github.io/vanilla-tilt.js/ -->  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/vanilla-tilt/1.7.0/vanilla-tilt.min.js"></script>
  <script>
    VanillaTilt.init(document.querySelectorAll(".card"), {
                max: 4,
                speed: 800,
    scale: 1.03,
    glare: true,
    "max-glare": 0.5,
        });
  </script>
</body>
</html>



Step 2: CSS Code


body {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100vh;
        margin: 0;
        font-family: 'Open Sans', sans-serif;
        background: #222;
        background-image: url('https://source.unsplash.com/1600x900/?landscape');
        font-size: 100%;
}
      
.card {
        background: rgba( 0, 0, 0, 0.30 );
        box-shadow: 0 8px 32px 0 rgba( 31, 38, 135, 0.37 );
        backdrop-filter: blur( 11.5px );
        -webkit-backdrop-filter: blur( 11.5px );
        border-radius: 10px;
        border: 1px solid rgba( 255, 255, 255, 0.18 );
        color: white;
        padding: 2em;
        border-radius: 30px;
        width: 100%;
        max-width: 420px;
        margin: 1em;
        overflow: hidden;
}
      
.search {
        display: flex;
        align-items: center;
        justify-content: center;
}
      
button {
        margin: 0.5em;
        border-radius: 50%;
        border: none;
        height: 44px;
        width: 44px;
        outline: none;
        background: rgba( 255, 255, 255, 0.25 );
        color: white;
        cursor: pointer;
        transition: 0.2s ease-in-out;
}
      
input.search-bar {
        border: none;
        outline: none;
        padding: 0.4em 1em;
        border-radius: 24px;
        background: rgba( 0, 0, 0, 0.30 );
        color: white;
        font-family: inherit;
        font-size: 105%;
        width: calc(100% - 100px);
}
      
button:hover {
        background: #7c7c7c6b;
}
      
h1.temp {
        margin: 0;
        margin-bottom: 0.4em;
}
      
.flex {
        display: flex;
        align-items: center;
}
      
.description {
        text-transform: capitalize;
        margin-left: 8px;
}
      
.weather.loading {
        visibility: hidden;
        max-height: 20px;
        position: relative;
}
      
.weather.loading:after {
        visibility: visible;
        content: "Loading...";
        color: white;
        position: absolute;
        top: 0;
        left: 20px;
}
      
.js-tilt-glare {
        border-radius: 10px;
}
      
a {
        margin-top: 7%;
        color: inherit;
        display: flex;
        justify-content: center;
        align-items: center;
}

Output Till Now

Realtime Weather Forecast App using JavaScript - Coding Torque

Step 3: JavaScript Code

/* Fetching Data from OpenWeatherMap API */
let weather = {
    apiKey: "6d055e39ee237af35ca066f35474e9df", // dont f with this api key, it does not belongs to me xd
    fetchWeather: function (city) {
    fetch(
        "https://api.openweathermap.org/data/2.5/weather?q=" +
        city +
        "&units=metric&appid=" +
        this.apiKey
        .then((response) => {
        if (!response.ok) {
            alert("Invalid location");
            throw new Error("Invalid location");
        }
        return response.json();
        })
        .then((data) => this.displayWeather(data));
    },
    displayWeather: function (data) {
    const { name } = data;
    const { icon, description } = data.weather[0];
    const { temp, humidity } = data.main;
    const { speed } = data.wind;
    document.querySelector(".city").innerText = "Weather in " + name;
    document.querySelector(".icon").src =
        "https://openweathermap.org/img/wn/" + icon + ".png";
    document.querySelector(".description").innerText = description;
    document.querySelector(".temp").innerText = temp + "°C";
    document.querySelector(".humidity").innerText =
        "Humidity: " + humidity + "%";
    document.querySelector(".wind").innerText =
        "Wind speed: " + speed + " km/h";
    document.querySelector(".weather").classList.remove("loading");
    document.body.style.backgroundImage =
        "url('https://source.unsplash.com/1600x900/?" + name + "')";
    },
    search: function () {
    this.fetchWeather(document.querySelector(".search-bar").value);
    },
};

/* Fetching Data from OpenCageData Geocoder */
let geocode = {
    reverseGeocode: function (latitude, longitude) {
    var apikey = "90a096f90b3e4715b6f2e536d934c5af";

    var api_url = "https://api.opencagedata.com/geocode/v1/json";

    var request_url =
        api_url +
        "?" +
        "key=" +
        apikey +
        "&q=" +
        encodeURIComponent(latitude + "," + longitude) +
        "&pretty=1" +
        "&no_annotations=1";

    var request = new XMLHttpRequest();
    request.open("GET", request_url, true);

    request.onload = function () {

        if (request.status == 200) {
        var data = JSON.parse(request.responseText);
        weather.fetchWeather(data.results[0].components.city);
        console.log(data.results[0].components.city)
        } else if (request.status <= 500) {

        console.log("unable to geocode! Response code: " + request.status);
        var data = JSON.parse(request.responseText);
        console.log("error msg: " + data.status.message);
        } else {
        console.log("server error");
        }
    };

    request.onerror = function () {
        console.log("unable to connect to server");
    };

    request.send(); 
    },
    getLocation: function() {
    function success (data) {
        geocode.reverseGeocode(data.coords.latitude, data.coords.longitude);
    }
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(success, console.error);
    }
    else {
        weather.fetchWeather("Manipal");
    }
    }
};

document.querySelector(".search button").addEventListener("click", function () {
    weather.search();
});

document
    .querySelector(".search-bar")
    .addEventListener("keyup", function (event) {
    if (event.key == "Enter") {
        weather.search();
    }
    });

weather.fetchWeather("Manipal");

document
    .querySelector(".search-bar")
    .addEventListener("keyup", function (event) {
    if (event.key == "Enter") {
        weather.search();
    }
    });

geocode.getLocation();

Final Output


Code Credits: @VarunBanka

Written by: Coding Torque | Piyush Patil

If you want me to code any project or post any specific post, feel free to DM me at IG @code.scientist or @codingtorque

 If you have any doubt or any project ideas feel free to Contact Us 

Hope you find this post helpful💖 

Follow us on Instagram for more projects like this👨‍💻 

Post a Comment

Previous Post Next Post