Home > Web Front-end > JS Tutorial > Project: Build a Weather App Using JavaScript and a Weather API

Project: Build a Weather App Using JavaScript and a Weather API

Linda Hamilton
Release: 2024-12-27 04:02:13
Original
516 people have browsed it

Project: Build a Weather App Using JavaScript and a Weather API

Date: December 18, 2024

Building a weather app is an excellent way to solidify your understanding of JavaScript, DOM manipulation, event handling, and API integration. This project will teach you how to fetch data from an API and display it dynamically on a webpage.


Project Overview

Features of the Weather App

  1. Fetch real-time weather data from a weather API (e.g., OpenWeatherMap).
  2. Input functionality: Users can search for weather details by entering a city name.
  3. Dynamic UI updates: Display temperature, humidity, and weather conditions dynamically.
  4. Error handling for invalid city names or API issues.

Step-by-Step Guide

1. Set Up Your Project

Create the necessary files for your project:

  • HTML: Structure the layout.
  • CSS: Style the app (optional for basic functionality).
  • JavaScript: Add interactivity and integrate the weather API.

2. Get a Weather API Key

Sign up at OpenWeatherMap and get an API key. You’ll use their API to fetch weather data.

Example API URL:

https://api.openweathermap.org/data/2.5/weather?q={city}&appid={API_KEY}&units=metric
Copy after login

3. Basic HTML Structure

Create a simple layout with an input field and a section to display weather information.

<!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>




<hr>

<h3>
  
  
  <strong>4. Styling (Optional)</strong>
</h3>

<p>Add some CSS to make your app visually appealing.<br>
</p>

<pre class="brush:php;toolbar:false">#weather-app {
  text-align: center;
  font-family: Arial, sans-serif;
  margin: 50px auto;
  width: 300px;
}

input, button {
  padding: 10px;
  margin: 10px 0;
}

#weather-result {
  margin-top: 20px;
}
Copy after login

5. Writing the JavaScript Code

DOM Manipulation and Event Handling

Use JavaScript to capture the user input, fetch data from the API, and display the results.

// JavaScript code for the weather app
const API_KEY = "your_api_key_here"; // Replace with your actual API key

document.getElementById("search-btn").addEventListener("click", () => {
  const city = document.getElementById("city-input").value;
  if (city) {
    fetchWeather(city);
  } else {
    displayError("Please enter a city name.");
  }
});

function fetchWeather(city) {
  const apiURL = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${API_KEY}&units=metric`;

  fetch(apiURL)
    .then(response => {
      if (!response.ok) {
        throw new Error("City not found");
      }
      return response.json();
    })
    .then(data => displayWeather(data))
    .catch(error => displayError(error.message));
}

function displayWeather(data) {
  document.getElementById("error-message").textContent = "";
  document.getElementById("city-name").textContent = `Weather in ${data.name}`;
  document.getElementById("temperature").textContent = `Temperature: ${data.main.temp}°C`;
  document.getElementById("description").textContent = `Condition: ${data.weather[0].description}`;
  document.getElementById("humidity").textContent = `Humidity: ${data.main.humidity}%`;
}

function displayError(message) {
  document.getElementById("error-message").textContent = message;
  document.getElementById("city-name").textContent = "";
  document.getElementById("temperature").textContent = "";
  document.getElementById("description").textContent = "";
  document.getElementById("humidity").textContent = "";
}
Copy after login

6. Testing the App

  1. Open the HTML file in a browser.
  2. Enter a city name (e.g., “London”) and click "Search".
  3. Verify that the weather details appear on the page.
  4. Test for invalid cities and empty input to ensure error messages display correctly.

Project: Build a Weather App Using JavaScript and a Weather API

My GitHub Repo here click

7. Features to Add Later (Optional Enhancements)

  1. Geolocation: Automatically detect the user's location and display the weather.
  2. Weather Icons: Use weather icons from the API response.
  3. Styling: Add animations or a responsive design for mobile users.
  4. Forecast: Show a 5-day weather forecast.

Project Summary

Building a weather app integrates many important JavaScript skills, such as:

  • Fetching and handling API data.
  • Dynamically manipulating the DOM.
  • Handling user input and displaying results interactively.

By completing this project, you’ll gain confidence in building more complex JavaScript applications.


Next Steps: Tomorrow, we’ll focus on Error Handling and Debugging in JavaScript, exploring techniques to identify and resolve issues effectively. Stay tuned!

The above is the detailed content of Project: Build a Weather App Using JavaScript and a Weather API. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template