task 4
Wed Apr 23 2025 01:41:08 GMT+0000 (Coordinated Universal Time)
Saved by @cciot
✅ Prerequisites 1. Sign up at https://openweathermap.org/api and get your API key. 2. Use the Current Weather Data API and 5 Day / 3 Hour Forecast API. 3. Include Chart.js via CDN in your HTML. --- 🔧 HTML Structure <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Weather Dashboard</title> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <style> table, th, td { border: 1px solid black; border-collapse: collapse; padding: 8px; } #weather-table, #forecast-table { margin: 20px 0; } </style> </head> <body> <h2>Weather Information</h2> <input type="text" id="city" placeholder="Enter City Name"> <button onclick="getWeather()">Get Weather</button> <div id="weather-table"></div> <div id="forecast-table"></div> <canvas id="forecastChart" width="600" height="300"></canvas> <script src="script.js"></script> </body> </html> --- ✏️ JavaScript (script.js) const apiKey = 'YOUR_API_KEY'; // Replace with your OpenWeatherMap API key async function getWeather() { const city = document.getElementById('city').value; if (!city) return alert('Please enter a city'); await getCurrentWeather(city); await getWeatherForecast(city); } async function getCurrentWeather(city) { const response = await fetch( `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric` ); const data = await response.json(); const html = ` <table> <tr><th>City</th><th>Min Temp (°C)</th><th>Max Temp (°C)</th><th>Humidity (%)</th></tr> <tr> <td>${data.name}</td> <td>${data.main.temp_min}</td> <td>${data.main.temp_max}</td> <td>${data.main.humidity}</td> </tr> </table> `; document.getElementById('weather-table').innerHTML = html; } async function getWeatherForecast(city) { const response = await fetch( `https://api.openweathermap.org/data/2.5/forecast?q=${city}&appid=${apiKey}&units=metric` ); const data = await response.json(); // Extract date and temperature every 8 entries (~24 hours) const forecasts = data.list.filter((_, index) => index % 8 === 0); const tableRows = forecasts.map(forecast => ` <tr> <td>${forecast.dt_txt.split(' ')[0]}</td> <td>${forecast.main.temp}</td> </tr> `).join(''); const table = ` <h3>5-Day Forecast</h3> <table> <tr><th>Date</th><th>Temperature (°C)</th></tr> ${tableRows} </table> `; document.getElementById('forecast-table').innerHTML = table; // Plot chart const labels = forecasts.map(f => f.dt_txt.split(' ')[0]); const temperatures = forecasts.map(f => f.main.temp); drawChart(labels, temperatures); } function drawChart(labels, data) { const ctx = document.getElementById('forecastChart').getContext('2d'); new Chart(ctx, { type: 'bar', data: { labels: labels, datasets: [{ label: 'Temperature (°C)', data: data, backgroundColor: 'rgba(54, 162, 235, 0.6)', borderColor: 'blue', borderWidth: 1 }] }, options: { responsive: true, scales: { y: { beginAtZero: false } } } }); }
Comments