Eighth project in JavaScript: Weather application using API

Eighth project in JavaScript: Weather application using API

Introduction

Keeping track of the current weather is important for many of us. What if you could create your own weather display app that provides accurate information about temperature, weather description, and an icon representing the current conditions? In this guide, you will learn how to build a simple web application to display weather using HTML, CSS, and JavaScript.

Obtaining the API Key from OpenWeatherMap

Before we dive into the code, we need an API key from OpenWeatherMap to retrieve current weather information. Follow these steps:

  1. Go to OpenWeatherMap and sign up.
  2. After registration, log in and go to your account.
  3. Obtain your API key from the "API keys" section.

API Key

Important: For the proper functioning of the application, it's recommended to use some form of a local server. You can, for example, use the Live Server extension in Visual Studio Code or run your own local server. This ensures that API calls work correctly, as some browsers block insecure (non-HTTPS) requests.

Creating the Weather Display App

Now let's move on to creating the actual application. We'll use HTML for structure, CSS for styling, and JavaScript for communication with the OpenWeatherMap API.

We will create three files:

  1. index.html
  2. style.css
  3. script.js

HTML (index.html)

Let's break down the structure of the HTML file that makes up our Weather Display App. This file serves as the foundation for our web application, defining its layout and content.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Weather</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <div id="weather-container">
    <h2>Weather</h2>
    <form id="city-form">
      <label for="city">Enter city: </label>
      <input type="text" id="city" name="city" required>
      <button type="submit">Show Weather</button>
    </form>
    <div id="temperature"></div>
    <div id="description"></div>
    <img id="weather-icon" alt="Weather">
  </div>

  <script src="script.js"></script>
</body>
</html>        

This HTML file provides the structure for our Weather Display App. It establishes the layout, includes essential metadata, and connects external styles and scripts to enhance the presentation and functionality of the application.


CSS (style.css)

body {
    font-family: 'Arial', sans-serif;
    background-color: #f0f0f0;
    margin: 100px;
    padding: 0;
    align-items: center;
  }
  
  #weather-container {
    text-align: center;
    margin-top: 50px;
    background-color: #fff;
    border-radius: 10px;
    padding: 20px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    width: 300px;
    margin: 0 auto;
  }
  
  h2 {
    color: #333;
  }
  
  form {
    margin-top: 20px;
  }
  
  label {
    display: block;
    margin-bottom: 10px;
  }
  
  input {
    width: 100%;
    padding: 8px;
    box-sizing: border-box;
    margin-bottom: 15px;
  }
  
  button {
    background-color: #4caf50;
    color: #fff;
    padding: 10px 15px;
    border: none;
    border-radius: 5px;
    cursor: pointer;
  }
  
  button:hover {
    background-color: #45a049;
  }
  
  #temperature, #description {
    margin: 10px 0;
    color: #333;
  }
  
  #weather-icon {
    width: 50px;
    height: 50px;
    margin-top: 10px;
  }        

JavaScript (script.js)

Let's delve into the content of the JavaScript file that handles the functionality of our Weather Display App. This file communicates with the OpenWeatherMap API and controls interactive elements on the page.

Function for Retrieving Weather

async function getWeather(city) {
  const apiKey = 'YOUR_API_KEY';
  const apiUrl = `https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${apiKey}`;

  try {
    const response = await fetch(apiUrl);
    const data = await response.json();

    const temperature = Math.round(data.main.temp);
    const description = data.weather[0].description;
    const iconCode = data.weather[0].icon;

    displayWeather(temperature, description, iconCode);
  } catch (error) {
    console.error('Error fetching weather data:', error);
  }
}        

his asynchronous getWeather() function provides the core functionality of the application. It calls the OpenWeatherMap API based on the entered city, processes the response, and displays weather information.

  • API Key: The constant apiKey holds our key for the OpenWeatherMap API.
  • API URL: The variable apiUrl constructs the API call URL with the specific city.
  • API Call: fetch is used to retrieve data from the API, and the data is then processed in JSON format.
  • Display Weather: The displayWeather() function displays temperature, description, and weather icon.


Event Listener for Form Submission

const cityForm = document.getElementById('city-form');

cityForm.addEventListener('submit', function (event) {
  event.preventDefault();

  const cityInput = document.getElementById('city');
  const userCity = cityInput.value;

  if (userCity) {
    getWeather(userCity);
  } else {
    alert('City not entered. Weather update not possible.');
  }
});        

This part of the code adds an event listener for form submission. When a user submits the form, we prevent its default behavior (event.preventDefault()) and retrieve the value of the entered city. If a city is provided, we call the getWeather function to fetch weather information; otherwise, we alert the user.


Function for Displaying Weather

function displayWeather(temperature, description, iconCode) {
  const temperatureElement = document.getElementById('temperature');
  const descriptionElement = document.getElementById('description');
  const iconElement = document.getElementById('weather-icon');

  temperatureElement.textContent = `Temperature: ${temperature} °C`;
  descriptionElement.textContent = `Description: ${description}`;
  iconElement.src = `https://openweathermap.org/img/w/${iconCode}.png`;
}        

This displayWeather function updates the page content based on the provided weather information. It modifies the content of elements for temperature, description, and the weather icon.


Conclusion

Creating a simple web application to display weather can be a great project to enhance your skills in HTML, CSS, and JavaScript. Now you know how to obtain an API key from OpenWeatherMap and build an interactive application that provides current weather information based on the entered city.

Getting More Information

The OpenWeatherMap API provides a wealth of weather data. You can expand your application to include additional information. For example, you can obtain:

  • Maximum and minimum temperature: data.main.temp_max and data.main.temp_min
  • Humidity: data.main.humidity
  • Wind speed: data.wind.speed
  • Wind direction: data.wind.deg
  • Sunrise and sunset: data.sys.sunrise and data.sys.sunset

Adding More Data to the Application

In our simple project, we focused mainly on the current temperature, weather description, and an icon representing current conditions. To add more information to the application, you can modify the displayWeather() function in the script.js file and add new elements for displaying additional data.

What's Next?

Get involved in the next phase of the project by expanding your application and adding more useful weather information. This way, you can apply your knowledge and create a more comprehensive web application.

We hope this guide has inspired you to create your own web projects and enhance your skills in web development!


You can find the complete code here GitHub




要查看或添加评论,请登录

?tefan Tusjak的更多文章

社区洞察

其他会员也浏览了