How to Build a Weather App Using APIs: A Step-by-Step Guide

29 Oct 2024 12:55 AM

In this project, we will create a weather app using the OpenWeatherMap API. The app will allow users to search for any city and display the current weather conditions, including temperature, weather type, humidity, and wind speed.

Project Overview

Features:

  • User searches for a city to get weather data.
  • Weather details are fetched from the OpenWeatherMap API.
  • Display information like temperature, weather description, humidity, and wind speed.

Step 1: Set Up the Project Structure

Create the following files:

/WeatherApp  
│
├── index.html  
├── styles.css  
└── script.js  

Step 2: Get Your API Key from OpenWeatherMap

  1. Go to OpenWeatherMap.
  2. Sign up for a free account and generate your API key.
  3. Keep the API key handy—we will use it in the code.

Step 3: Write HTML (index.html)

<!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>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <div class="container">
    <h1>Weather App</h1>
    <div class="search-box">
      <input type="text" id="city-input" placeholder="Enter city name...">
      <button id="search-btn">Search</button>
    </div>
    <div id="weather-info" class="hidden">
      <h2 id="city-name"></h2>
      <p id="weather-description"></p>
      <p>Temperature: <span id="temperature"></span>°C</p>
      <p>Humidity: <span id="humidity"></span>%</p>
      <p>Wind Speed: <span id="wind-speed"></span> km/h</p>
    </div>
    <p id="error-message" class="hidden">City not found. Please try again.</p>
  </div>
  <script src="script.js"></script>
</body>
</html>

Step 4: Style the App (styles.css)

body {
  font-family: Arial, sans-serif;
  background-color: #e0e0e0;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  margin: 0;
}

.container {
  width: 400px;
  padding: 20px;
  background-color: white;
  box-shadow: 0 0 15px rgba(0, 0, 0, 0.1);
  border-radius: 10px;
  text-align: center;
}

.search-box {
  margin-bottom: 20px;
}

input {
  padding: 10px;
  width: 70%;
  border: 1px solid #ccc;
  border-radius: 5px;
  margin-right: 10px;
}

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

button:hover {
  background-color: #218838;
}

.hidden {
  display: none;
}

#error-message {
  color: red;
  margin-top: 10px;
}

Step 5: Add JavaScript Logic (script.js)

const apiKey = 'your_api_key'; // Replace with your OpenWeatherMap API key

// Select elements
const searchBtn = document.getElementById('search-btn');
const cityInput = document.getElementById('city-input');
const weatherInfo = document.getElementById('weather-info');
const errorMessage = document.getElementById('error-message');

const cityNameElem = document.getElementById('city-name');
const weatherDescElem = document.getElementById('weather-description');
const temperatureElem = document.getElementById('temperature');
const humidityElem = document.getElementById('humidity');
const windSpeedElem = document.getElementById('wind-speed');

// Event listener for the search button
searchBtn.addEventListener('click', () => {
  const city = cityInput.value.trim();
  if (city) {
    fetchWeatherData(city);
  }
});

// Fetch weather data from OpenWeatherMap API
async function fetchWeatherData(city) {
  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();
    if (data.cod === 200) {
      displayWeatherData(data);
    } else {
      showError('City not found. Please try again.');
    }
  } catch (error) {
    showError('An error occurred. Please try again.');
  }
}

// Display weather data on the page
function displayWeatherData(data) {
  errorMessage.classList.add('hidden');
  weatherInfo.classList.remove('hidden');

  cityNameElem.textContent = data.name;
  weatherDescElem.textContent = data.weather[0].description;
  temperatureElem.textContent = data.main.temp.toFixed(1);
  humidityElem.textContent = data.main.humidity;
  windSpeedElem.textContent = (data.wind.speed * 3.6).toFixed(1); // Convert m/s to km/h
}

// Show error messages
function showError(message) {
  weatherInfo.classList.add('hidden');
  errorMessage.textContent = message;
  errorMessage.classList.remove('hidden');
}

Step 6: Run the Weather App

  1. Open index.html in your browser.
  2. Enter a city name and click the Search button.
  3. The current weather data for the city will be displayed.

Explanation

  1. API Integration:

    • We fetch weather data from the OpenWeatherMap API using the fetch() method.
    • The apiKey is used to authenticate API requests.
  2. Temperature and Wind Conversion:

    • The temperature is shown in Celsius by setting units=metric in the API URL.
    • Wind speed is converted from meters per second to kilometers per hour.
  3. Error Handling:

    • If the city is not found, we display a user-friendly error message.

Possible Enhancements

  • Geolocation Support: Automatically detect the user’s location and show the weather.
  • 5-day Forecast: Use the /forecast endpoint of the API to display a weather forecast.
  • Background Change: Update the background image based on the weather (e.g., rainy, sunny).
  • Loader Animation: Add a loader while fetching data.

Conclusion

This weather app demonstrates how to fetch data from an API and display it dynamically using JavaScript. With a simple UI and essential weather information, this project is a great starting point for learning API integration and front-end development.

Let me know if you want to extend the app with more features!





 

 

 

 

1
16