Weather App using HTML,CSS and JS
Tags: javascript, webdev, tutorial, beginners
Published: 2022-02-10 09:55:12

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](https://openweathermap.org/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`.
```html
<!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>
```

##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](https://www.w3schools.com/html/html5_geolocation.asp)

So, now we declare the variables in our program 

```javascript
let city = document.querySelector('.cityname');
let btn = document.querySelector('.btn');
let locBtn = document.querySelector('.locBtn');
let output = document.getElementById('output');
```
Now add `addEventListener` to `btn`. We listen for a `click` event and on click we will call `checkWeather()` function.

```javascript
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"));
}
```

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()`

```javascript
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.");
    }
}

```

Hope this tutorial is helpful for you 
If you wish to support my work [buy me a coffee](https://buymeacoffee.com/devrohit)