Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING BASH RUST

Brtest Tutorial


Project: Weather App

In this project, you will create a simple Weather App that shows the current weather for your location. You will use the Fetch API to get weather data from an online service, and the Geolocation API to detect the user's position.


Project Overview

This app will:

  • Ask for the user's location
  • Fetch live weather data using a public API
  • Display temperature, description, and city name
  • Handle loading states and errors gracefully

HTML Structure

We’ll start with a simple container that shows the weather info and a button to trigger location detection.

Example

Basic HTML for the weather app:

<div class='weather-app'>
  <h2>Weather App</h2>
  <p id='status'>Click below to get your weather</p>
  <button id='getWeather'>Get Weather</button>
  <div id='weatherInfo' class='hidden'>
    <h3 id='city'></h3>
    <p id='temp'></p>
    <p id='desc'></p>
  </div>
</div>
Try it Yourself »

CSS Styling

Use simple styling to center the app and make it visually clear.

Example

Weather app styling:

body {
  font-family: Arial, sans-serif;
  background: linear-gradient(to bottom, #87CEEB, #f4f4f4);
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  margin: 0;
}

.weather-app {
  text-align: center;
  background: white;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
  max-width: 300px;
}

button {
  background: #111;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 6px;
  cursor: pointer;
  margin-top: 10px;
}

button:hover { background: #333; }
.hidden { display: none; }
Try it Yourself »

JavaScript Logic

This is where we combine the Geolocation API and Fetch API to get live weather data. You can use the free Open-Meteo API for this example.

Example

Get weather data with Fetch:

<script>
const statusEl = document.getElementById('status');
const btn = document.getElementById('getWeather');
const info = document.getElementById('weatherInfo');
const cityEl = document.getElementById('city');
const tempEl = document.getElementById('temp');
const descEl = document.getElementById('desc');

btn.addEventListener('click', () => {
  statusEl.textContent = 'Getting location...';
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showWeather, showError);
  } else {
    statusEl.textContent = 'Geolocation not supported';
  }
});

function showWeather(position) {
  const lat = position.coords.latitude;
  const lon = position.coords.longitude;
  statusEl.textContent = 'Fetching weather...';

  fetch(`https://api.open-meteo.com/v1/forecast?latitude=${lat}&longitude=${lon}¤t_weather=true`)
    .then(res => res.json())
    .then(data => {
      const weather = data.current_weather;
      cityEl.textContent = 'Your Location';
      tempEl.textContent = 'Temperature: ' + weather.temperature + '°C';
      descEl.textContent = 'Windspeed: ' + weather.windspeed + ' km/h';
      info.classList.remove('hidden');
      statusEl.textContent = 'Weather data loaded!';
    })
    .catch(() => {
      statusEl.textContent = 'Failed to get weather data.';
    });
}

function showError(error) {
  statusEl.textContent = 'Unable to get location.';
}
</script>
Try it Yourself »

How It Works

  1. The button triggers the getCurrentPosition() function.
  2. The coordinates (latitude and longitude) are used to call the Open-Meteo API.
  3. JavaScript extracts the temperature and windspeed from the JSON response.
  4. The DOM updates to show the weather data dynamically.

Error Handling

Always check for possible errors when dealing with APIs or user permissions.

Example

Handle geolocation errors:

function showError(error) {
  switch(error.code) {
    case error.PERMISSION_DENIED:
      statusEl.textContent = 'User denied geolocation request.';
      break;
    case error.POSITION_UNAVAILABLE:
      statusEl.textContent = 'Location information unavailable.';
      break;
    case error.TIMEOUT:
      statusEl.textContent = 'The request timed out.';
      break;
    default:
      statusEl.textContent = 'An unknown error occurred.';
  }
}

Bonus Ideas

  • Display an emoji or icon for weather conditions (☀️, 🌧️, 🌩️).
  • Allow the user to search for a city manually.
  • Convert temperature between Celsius and Fahrenheit.
  • Show the last updated time automatically.

Summary

  • You built a live weather app using fetch() and geolocation.
  • Learned how to handle JSON data and update the DOM dynamically.
  • Practiced working with APIs, loading states, and error handling.

Next, you'll move on to **Building Complete Websites**, combining everything you’ve learned into structured, multi-page web projects.

Next » Building Complete Websites

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2025 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.