DEV Community

Rohit Sharma
Rohit Sharma

Posted on

Weather App using HTML,CSS and JS

Hello everyone, today we'll be going to create a weather app with help of HTML,CSS and Javascript. For this we'll be using open weather map api. Just follow the basic steps to get your free API ID.

HTML

We need city name as a input from user and two button.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WeatHere</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="container">
            <h1>Weather All-Around</h1>
            <div id="input">
                <input type="text" class="cityname">
                <input type="submit" value="Check Weather" class="btn">
                <button class="locBtn"><img src="https://img.icons8.com/external-kmg-design-outline-color-kmg-design/32/000000/external-pin-map-and-navigation-kmg-design-outline-color-kmg-design-2.png"/></button>

            </div>
            <div id="output">

            </div>
    </div>
    <script src="main.js"></script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

CSS

You can style this as your wish.

Javascript

You should check the documentation of open weather API for more clarity.

The basic structure url looks like this
https://api.openweathermap.org/data/2.5/weather?q=cityName&units=metric&appid=1ebc5861bba83e0214cd8df3b995ffca

So, every time we have to change the value of cityName.

In case, we don't know the city name then we can use our device location to get weather update. For this the url looks like this
https://api.openweathermap.org/data/2.5/weather?lat=latitude&lon=longitude&units=metric&appid=1ebc5861bba83e0214cd8df3b995ffca.

So, every time we have to change the value of latitude and longitude for this we use Geolocation API

So, now we declare the variables in our program

let city = document.querySelector('.cityname');
let btn = document.querySelector('.btn');
let locBtn = document.querySelector('.locBtn');
let output = document.getElementById('output');
Enter fullscreen mode Exit fullscreen mode

Now add addEventListener to btn. We listen for a click event and on click we will call checkWeather() function.

btn.addEventListener('click',checkWeather);
function checkWeather(){
    fetch('https://api.openweathermap.org/data/2.5/weather?q='+city.value+'&units=metric&appid=1ebc5861bba83e0214cd8df3b995ffca')
    .then(response => response.json())
    .then(data =>{
        console.log(data);
        output.innerHTML = data['main']['temp']+'°C'+`<br>`+data['weather'][0]['description'];
        output.style.cssText ='background:#c3ffe5; text-align:center; width:150px;'    
    })
    .catch(err=>alert("error"));
}
Enter fullscreen mode Exit fullscreen mode

If user want to check weather using his current location. We have to add addEventListener to locBtn and on clicking the button we call another function showPosition()

locBtn.addEventListener('click',showPosition);
function showPosition() {
    if(navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
            var lat = position.coords.latitude;
            var lon = position.coords.longitude;
            // document.getElementById("lat").innerHTML = lat;
            // document.getElementById("lon").innerHTML = lon;
            fetch('https://api.openweathermap.org/data/2.5/weather?lat='+lat+'&lon='+lon+'&units=metric&appid=1ebc5861bba83e0214cd8df3b995ffca')
            .then(response => response.json())
            .then(data =>{
                output.innerHTML =`<h4>`+ data['main']['temp']+'°C and Location: ' +data['name']+`<br>`+data['weather'][0]['description']+`</h4>`;
                output.style.cssText ='background:#c3ffe5; text-align:center; width:150px;'    
    })
    .catch(err=>alert("error"));

        });

    } else {
        alert("Sorry, your browser does not support HTML5 geolocation.");
    }
}

Enter fullscreen mode Exit fullscreen mode

Hope this tutorial is helpful for you
If you wish to support my work buy me a coffee

Top comments (0)