4d
Sun Apr 06 2025 17:53:15 GMT+0000 (Coordinated Universal Time)
Saved by
@exam3
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<h3>Temperature Forecast Chart</h3>
<input id="city" placeholder="Enter city">
<button onclick="drawChart()">Get Forecast</button>
<canvas id="tempChart" width="400" height="200"></canvas>
<script>
async function drawChart() {
const city = document.getElementById("city").value;
const key = "36f9af4e269fe80b4cda0e7e8af0809d"; // Replace with your OpenWeatherMap API key
const res = await fetch(`https://api.openweathermap.org/data/2.5/forecast?q=${city}&appid=${key}&units=metric`);
const data = await res.json();
const labels = [];
const temps = [];
data.list.forEach((item, i) => {
if (i % 8 === 0) { // every 24 hours (8 x 3-hour slots)
labels.push(item.dt_txt.split(" ")[0]);
temps.push(item.main.temp);
}
});
new Chart(document.getElementById("tempChart"), {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: 'Temperature (°C)',
data: temps,
backgroundColor: 'rgba(54, 162, 235, 0.6)'
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
}
</script>
</body>
</html>
content_copyCOPY
Comments