Real-time weather updates on home page

Loading

Displaying real-time weather on a homepage improves user experience, especially for travel, events, local news, or lifestyle websites. With a weather API, you can fetch current weather data like temperature, humidity, weather conditions, and more based on location.

We’ll cover:

  • Choosing a weather API
  • Getting an API key
  • Writing front-end JavaScript to fetch and display data
  • Formatting and styling the output
  • Optional enhancements like icons and geolocation

Step 1: Choose a Weather API Provider

Popular weather APIs include:

In this tutorial, we’ll use OpenWeatherMap as it offers free-tier access and easy implementation.


Step 2: Create an OpenWeatherMap Account and Get API Key

  1. Go to https://openweathermap.org/
  2. Click Sign Up and create an account
  3. Go to your profile and find the API Keys section
  4. Copy the default key or create a new one

Step 3: Prepare Your HTML Structure

Create a basic HTML file:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Weather Update</title>
<style>
body { font-family: Arial; padding: 20px; }
#weather { border: 1px solid #ccc; padding: 20px; border-radius: 10px; width: 300px; }
</style>
</head>
<body>

<h2>Current Weather</h2>
<div id="weather">
<p id="location">Loading...</p>
<p id="description"></p>
<p id="temperature"></p>
<p id="humidity"></p>
</div>

<script src="weather.js"></script>

</body>
</html>

Step 4: Create JavaScript to Fetch Weather Data

In weather.js, add:

const apiKey = 'YOUR_API_KEY'; // Replace with your actual API key
const city = 'New York'; // You can change this or make it dynamic

const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${apiKey}`;

fetch(url)
.then(response => response.json())
.then(data => {
document.getElementById('location').textContent = `Weather in ${data.name}`;
document.getElementById('description').textContent = data.weather[0].description;
document.getElementById('temperature').textContent = `Temperature: ${data.main.temp} °C`;
document.getElementById('humidity').textContent = `Humidity: ${data.main.humidity}%`;
})
.catch(error => {
document.getElementById('location').textContent = 'Unable to load weather';
console.error('Error fetching weather:', error);
});

Note: units=metric returns Celsius. Use imperial for Fahrenheit.


Step 5: Styling the Weather Box (Optional)

Update the CSS inside the <style> tag:

#weather {
background: #f1f1f1;
color: #333;
text-align: left;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
}

Step 6: Add Weather Icons (Optional)

OpenWeatherMap provides icon codes:

<img id="icon" src="" alt="weather icon">

Update your JS to include:

const iconCode = data.weather[0].icon;
document.getElementById('icon').src = `https://openweathermap.org/img/wn/${iconCode}@2x.png`;

Step 7: Use Geolocation to Get Local Weather (Optional)

Replace the static city with the user’s location:

navigator.geolocation.getCurrentPosition(position => {
const lat = position.coords.latitude;
const lon = position.coords.longitude;

const geoUrl = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&units=metric&appid=${apiKey}`;

fetch(geoUrl)
.then(response => response.json())
.then(data => {
document.getElementById('location').textContent = `Weather in ${data.name}`;
document.getElementById('description').textContent = data.weather[0].description;
document.getElementById('temperature').textContent = `Temperature: ${data.main.temp} °C`;
document.getElementById('humidity').textContent = `Humidity: ${data.main.humidity}%`;

const iconCode = data.weather[0].icon;
document.getElementById('icon').src = `https://openweathermap.org/img/wn/${iconCode}@2x.png`;
});
});

Note: Geolocation requires HTTPS to work in browsers.


Step 8: Make the Widget Responsive (Optional)

Add media queries to ensure it works on mobile:

@media (max-width: 600px) {
#weather {
width: 100%;
}
}

Step 9: Error Handling and Fallback

Add error handling for unsupported geolocation:

if (!navigator.geolocation) {
document.getElementById('location').textContent = 'Geolocation is not supported by your browser';
}

Handle API errors:

.catch(error => {
document.getElementById('location').textContent = 'Unable to retrieve weather data';
});

Step 10: Embed in Your Homepage

You can now include this weather box anywhere in your homepage layout by including the weather.js file and the HTML #weather block.


Bonus: Auto-Update Weather Every 10 Minutes

Add this to your script to refresh periodically:

setInterval(() => {
location.reload(); // Refresh the entire page
}, 600000); // 10 minutes = 600000 ms

Or refetch only the weather data:

setInterval(fetchWeatherData, 600000); // If you wrap the API call in a function

Leave a Reply

Your email address will not be published. Required fields are marked *