-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
110 lines (92 loc) · 3.95 KB
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
function getWeather() {
const apiKey = 'YOUR_API_KEY_HERE';
const city = document.getElementById('city').value;
if (!city) {
alert('Please enter a city');
return;
}
const currentWeatherUrl = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}`;
const forecastUrl = `https://api.openweathermap.org/data/2.5/forecast?q=${city}&appid=${apiKey}`;
// Fetch current weather data
fetch(currentWeatherUrl)
.then(response => response.json())
.then(data => {
displayWeather(data);
})
.catch(error => {
console.error('Error fetching current weather data:', error);
alert('Error fetching current weather data. Please try again.');
});
// Fetch forecast data
fetch(forecastUrl)
.then(response => response.json())
.then(data => {
// Check if `data.list` exists and is an array before passing to `displayHourlyForecast`
if (data && data.list && Array.isArray(data.list)) {
displayHourlyForecast(data.list);
} else {
console.error('Unexpected forecast data structure:', data);
alert('Error fetching forecast data. Please try again.');
}
})
.catch(error => {
console.error('Error fetching hourly forecast data:', error);
alert('Error fetching hourly forecast data. Please try again.');
});
}
function displayWeather(data) {
const tempDivInfo = document.getElementById('temp-div');
const weatherInfoDiv = document.getElementById('weather-info');
const weatherIcon = document.getElementById('weather-icon');
const hourlyForecastDiv = document.getElementById('hourly-forecast');
// Clear previous content
weatherInfoDiv.innerHTML = '';
hourlyForecastDiv.innerHTML = '';
tempDivInfo.innerHTML = '';
// Check if the API returned an error code
if (data.cod === '401' || data.cod === '404') {
weatherInfoDiv.innerHTML = `<p>Error: ${data.message}</p>`;
return;
}
if (data.cod === 200) {
const cityName = data.name;
const temperature = Math.round(data.main.temp - 273.15); // Convert to Celsius
const description = data.weather[0].description;
const iconCode = data.weather[0].icon;
const iconUrl = `https://openweathermap.org/img/wn/${iconCode}@4x.png`;
const temperatureHTML = `<p>${temperature}°C</p>`;
const weatherHtml = `<p>${cityName}</p><p>${description}</p>`;
tempDivInfo.innerHTML = temperatureHTML;
weatherInfoDiv.innerHTML = weatherHtml;
weatherIcon.src = iconUrl;
weatherIcon.alt = description;
showImage();
} else {
console.error("Unexpected response from API", data);
alert("Error fetching weather data. Please try again.");
}
}
function displayHourlyForecast(hourlyData) {
const hourlyForecastDiv = document.getElementById('hourly-forecast');
// Slice the next 8 items (3-hour intervals) for the next 24 hours
const next24Hours = hourlyData.slice(0, 8);
next24Hours.forEach(item => {
const dateTime = new Date(item.dt * 1000); // Convert timestamp to milliseconds
const hour = dateTime.getHours();
const temperature = Math.round(item.main.temp - 273.15); // Convert to Celsius
const iconCode = item.weather[0].icon;
const iconUrl = `https://openweathermap.org/img/wn/${iconCode}.png`;
const hourlyItemHtml = `
<div class="hourly-item">
<span>${hour}:00</span>
<img src="${iconUrl}" alt="Hourly Weather Icon">
<span>${temperature}°C</span>
</div>
`;
hourlyForecastDiv.innerHTML += hourlyItemHtml;
});
}
function showImage() {
const weatherIcon = document.getElementById('weather-icon');
weatherIcon.style.display = 'block'; // Make the image visible once it's loaded
}