Create a Dynamic Weather Report with HTML & JavaScript
Hey everyone!
Are you looking to add a real-time weather report to your website? Look no further! Today, I'm excited to share a quick and easy tutorial on how to create a dynamic weather report for your website using HTML and JavaScript. In just under a minute, you can have a real-time weather app up and running. Let's dive in!
Here's what the code does:
- Grabs Your Location: The code uses an API from ipapi.co to fetch your approximate location (city, region) based on your IP address.
- Fetches Weather Data: Once it has your location, the code uses the OpenWeatherMap API to retrieve the current weather data for your area. You'll need a free API key from OpenWeatherMap to use this functionality.
- Displays the Weather: The code then takes the weather data and formats it into a user-friendly report that displays:
- Location (City, Country)
- Timezone
- Current Weather Conditions (e.g. sunny, cloudy, rainy)
- Current Temperature (°C)
- Humidity (%)
- Wind Speed (m/s)
Adding this code to a basic HTML framework creates a handy weather report that automatically updates with your location!
Step 1: Setting Up the HTML Structure
First, let's create a simple HTML structure. We'll add a heading for our weather report and a div to 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 Report</title>
</head>
<body>
<h1>Weather Report</h1>
<div id="weatherData"></div>
<script src="weather.js"></script>
</body>
</html>
Step 2: Fetching User Location Data
window.addEventListener('load', () => {fetch('https://ipapi.co/json/').then(response => response.json()).then(data => {const { latitude, longitude } = data;// Fetch weather data using OpenWeatherMap APIconst apiKey = 'a8e71c9932b20c4ceb0aed183e6a83bb';const openWeatherMapUrl = `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${apiKey}&units=metric`;fetch(openWeatherMapUrl).then(response => response.json()).then(weatherData => {displayWeatherData(weatherData);}).catch(error => {console.error('Error fetching weather data:', error);});}).catch(error => {console.error('Error fetching location data:', error);});});
Step 3: Displaying the Weather Data
function displayWeatherData(weatherData) {const weatherReport = `<p>Location: ${weatherData.name}, ${weatherData.sys.country}</p><p>Timezone: ${weatherData.timezone}</p><p>Current Weather: ${weatherData.weather[0].description}</p><p>Temperature: ${weatherData.main.temp} °C</p><p>Humidity: ${weatherData.main.humidity}%</p><p>Wind Speed: ${weatherData.wind.speed} m/s</p>`;document.getElementById('weatherData').innerHTML = weatherReport;}