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.
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
Open index.html in your browser.
Enter a city name and click the Search button.
The current weather data for the city will be displayed.
Explanation
API Integration:
We fetch weather data from the OpenWeatherMap API using the fetch() method.
The apiKey is used to authenticate API requests.
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.
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!