Weather App to fetch/display weather data using API

Introduction

Building a weather application that fetches and displays weather data using an API is an excellent project for developers looking to enhance their skills in JavaScript and API integration. This guide will walk you through the essential steps to create a functional weather app, including setting up the environment, fetching data from a weather API, and displaying the information on a web page.

A weather app typically allows users to input a location (such as a city name) and receive real-time weather information, including temperature, humidity, wind speed, and more. To achieve this, we will use a weather API, such as OpenWeatherMap or Tomorrow.io, to fetch the required data.

Step 1. Set up your Development Environment.

Before diving into coding, ensure you have the following,

  • A code editor (like Visual Studio Code).
  • A basic understanding of HTML, CSS, and JavaScript.
  • An account with a weather API provider to obtain an API key.

Register for an API Key

  1. Choose an API Provider: For this example, we will use OpenWeatherMap.
  2. Sign Up: Create an account on their website and obtain your API key from the API management section.

Step 2. Create the HTML Structure.

Create a weather-app-1.html file with a simple structure to accept user input and display the weather data.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Weather App</title>
    <style>
 </style>
</head>
<body>
 <script>

    <div class="container">
        <h1>Weather App</h1>
        <input type="text" id="cityInput" placeholder="Enter city name">
        <button id="getWeather">Get Weather</button>
        <div id="weatherDisplay"></div>
    </div>
 </script>
</body>

</html>

Step 3. Style the Application (Optional)

Place the CSS in style tag.

body 
{
    font-family: Arial, sans-serif;
    background-color: #f0f8ff; /* Light background for better readability */
    margin: 0;
    padding: 0;
}

.container {
    max-width: 600px;
    padding: 20px;
    background: white;
    border-radius: 5px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    margin: 50px auto;
    text-align: center;
}

h1 {
    color: #333;
    font-size: 2rem;
}

input {
    width: 80%;
    padding: 10px;
    margin-bottom: 20px;
    font-size: 1rem;
    border: 1px solid #ccc;
    border-radius: 5px;
}

button {
    padding: 10px;
    background-color: #4CAF50;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
}

button:hover {
    background-color: #45a049;
}

#weatherDisplay {
    margin-top: 20px;
    font-size: 1.2rem;
    color: #333;
}

#weatherDisplay h2 {
    font-size: 1.5rem;
}

Step 4. Fetch Weather Data from the API.

Now, we will write JavaScript code to fetch data from the weather API. Add the javascript in script tag.

// Place your actual API key here
const apiKey = 'd28057b8ccf2efb88608f67e49612b41'; // Use your OpenWeatherMap API key here

const getWeatherButton = document.getElementById('getWeather');
const weatherDisplay = document.getElementById('weatherDisplay');

// Event listener for the "Get Weather" button
getWeatherButton.addEventListener('click', () => {
    const city = document.getElementById('cityInput').value.trim();
    if (city === "") {
        weatherDisplay.innerHTML = "<p>Please enter a city name!</p>";
    } else {
        fetchWeatherData(city);
    }
});

// Function to fetch weather data from OpenWeatherMap API
function fetchWeatherData(city) {
    const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`;

    // Fetch data from the OpenWeatherMap API
    fetch(url)
        .then(response => {
            if (!response.ok) {
                throw new Error('City not found');
            }
            return response.json();
        })
        .then(data => displayWeather(data))
        .catch(error => {
            weatherDisplay.innerHTML = `<p>${error.message}</p>`;
        });
}

// Function to display the fetched weather data
function displayWeather(data) {
    const { main, wind, weather } = data;

    // Display weather details
    weatherDisplay.innerHTML = `
        <h2>Weather in ${data.name}</h2>
        <p><strong>Temperature:</strong> ${main.temp}°C</p>
        <p><strong>Humidity:</strong> ${main.humidity}%</p>
        <p><strong>Wind Speed:</strong> ${wind.speed} m/s</p>
        <p><strong>Condition:</strong> ${weather[0].description}</p>
    `;
}

API Key and Elements

The API key (apiKey) allows access to weather data from OpenWeatherMap, the getWeatherButton is the button the user clicks to trigger the weather request, and weatherDisplay is the element where the fetched weather information will be shown.

Button Click Event

  • When the user clicks the "Get Weather" button, the city name is taken from the input field.
  • If no city is entered, the app prompts the user to enter a city.
  • If a valid city is entered, the code calls the fetchWeatherData() function to retrieve the weather data.

fetchWeatherData() Function

  • This function constructs a URL using the city name and API key to request weather data from OpenWeatherMap.
  • It retrieves the weather data and either displays it or shows an error message if the city is not found.

displayWeather() Function

This function takes the weather data returned by the API and displays the temperature, humidity, wind speed, and weather conditions on the page.

Step 5. Test your Weather App

Open your Weather app.html file in a web browser. Enter different city names in the input field and click "Get Weather" to see if it correctly fetches and displays the weather information.

Conclusion

Creating a weather app is a rewarding project that enhances your skills in JavaScript and working with APIs. By following these steps, you can build a functional application that provides real-time weather data based on user input. As you become more comfortable with these concepts, consider adding features like forecasts for multiple days or integrating additional APIs for more detailed information.

Happy coding!