-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
237 lines (205 loc) · 8.1 KB
/
script.js
File metadata and controls
237 lines (205 loc) · 8.1 KB
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
const apiKey = "de846b0858ddcfaa2c8c0db760eade14";
const apiUrl = "https://api.openweathermap.org/data/2.5/weather?units=metric&q=";
const apiUrlByCoords = "https://api.openweathermap.org/data/2.5/weather?units=metric&lat=";
const forecastUrl = "https://api.openweathermap.org/data/2.5/forecast?units=metric&q=";
const forecastUrlByCoords = "https://api.openweathermap.org/data/2.5/forecast?units=metric&lat=";
const searchBox = document.querySelector(".search input");
const searchBtn = document.querySelector(".search button");
const locationBtn = document.querySelector(".location-btn");
const weatherIcon = document.querySelector(".weather-icon");
const progressBar = document.getElementsByClassName('progress-bar')[0];
let progressInterval;
let weatherData = null;
let forecastData = null;
let hasError = false;
async function checkWeather(city) {
try {
const response = await fetch(apiUrl + city + `&appid=${apiKey}`);
if (!response.ok) {
hasError = true;
} else {
weatherData = await response.json();
hasError = false;
}
} catch (error) {
console.error("Error fetching weather:", error);
hasError = true;
}
}
async function checkWeatherByCoords(lat, lon) {
try {
const response = await fetch(apiUrlByCoords + lat + `&lon=${lon}&appid=${apiKey}`);
if (!response.ok) {
hasError = true;
} else {
weatherData = await response.json();
hasError = false;
}
} catch (error) {
console.error("Error fetching weather:", error);
hasError = true;
}
}
async function checkForecast(city) {
try {
const response = await fetch(forecastUrl + city + `&appid=${apiKey}`);
if (!response.ok) {
forecastData = null;
} else {
forecastData = await response.json();
}
} catch (error) {
console.error("Error fetching forecast:", error);
forecastData = null;
}
}
async function checkForecastByCoords(lat, lon) {
try {
const response = await fetch(forecastUrlByCoords + lat + `&lon=${lon}&appid=${apiKey}`);
if (!response.ok) {
forecastData = null;
} else {
forecastData = await response.json();
}
} catch (error) {
// Display forecast
displayForecast();
console.error("Error fetching forecast:", error);
forecastData = null;
}
}
function displayWeather() {
if (hasError) {
document.querySelector(".error").style.display = "block";
document.querySelector(".weather").style.display = "none";
} else {
const data = weatherData;
document.querySelector(".city").innerHTML = data.name;
document.querySelector(".temp").innerHTML = Math.round(data.main.temp) + "°c";
document.querySelector(".humidity").innerHTML = data.main.humidity + "%";
document.querySelector(".wind").innerHTML = data.wind.speed + " km/h";
if (data.weather[0].main == "Clouds") {
weatherIcon.src = "images/clouds.png";
} else if (data.weather[0].main == "Clear") {
weatherIcon.src = "images/clear.png";
} else if (data.weather[0].main == "Rain") {
weatherIcon.src = "images/rain.png";
} else if (data.weather[0].main == "Drizzle") {
weatherIcon.src = "images/drizzle.png";
} else if (data.weather[0].main == "Mist") {
weatherIcon.src = "images/mist.png";
}
document.querySelector(".weather").style.display = "block";
document.querySelector(".error").style.display = "none";
// Display forecast
displayForecast();
}
}
function displayForecast() {
const forecastContainer = document.getElementById("forecast-container");
forecastContainer.innerHTML = "";
if (!forecastData || !forecastData.list) return;
// Get forecast for next 5 days (every 24 hours)
const dailyForecasts = {};
forecastData.list.forEach(item => {
const date = new Date(item.dt * 1000);
const day = date.toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric' });
// Keep only one forecast per day (the first one we encounter)
if (!dailyForecasts[day]) {
dailyForecasts[day] = item;
}
});
// Display up to 5 days
Object.keys(dailyForecasts).slice(0, 5).forEach(day => {
const forecast = dailyForecasts[day];
const temp = Math.round(forecast.main.temp);
const weather = forecast.weather[0].main;
let iconSrc = "images/clouds.png";
if (weather == "Clouds") iconSrc = "images/clouds.png";
else if (weather == "Clear") iconSrc = "images/clear.png";
else if (weather == "Rain") iconSrc = "images/rain.png";
else if (weather == "Drizzle") iconSrc = "images/drizzle.png";
else if (weather == "Mist") iconSrc = "images/mist.png";
const forecastHTML = `
<div class="forecast-item">
<p class="forecast-day">${day}</p>
<img src="${iconSrc}" alt="${weather}">
<p class="forecast-temp">${temp}°c</p>
<p>${weather}</p>
</div>
`;
forecastContainer.innerHTML += forecastHTML;
});
}
function resetProgressBar() {
clearInterval(progressInterval); // stop old animation
progressBar.style.setProperty('--width', 0); // reset to 0
progressBar.style.display = 'flex'; // show bar
progressBar.setAttribute('data-label', 'Loading...');
}
function startProgressBar() {
resetProgressBar();
progressInterval = setInterval(() => {
const computedStyle = getComputedStyle(progressBar);
const width = parseFloat(computedStyle.getPropertyValue('--width')) || 0;
if (width < 100) {
progressBar.style.setProperty('--width', width + 0.5);
} else {
clearInterval(progressInterval);
progressBar.style.display = 'none';
}
}, 5);
}
async function performSearch() {
progressBar.style.display = "flex";
progressBar.style.setProperty('--width', 0);
clearInterval(progressInterval);
weatherData = null;
hasError = false;
document.querySelector(".error").style.display = "none";
document.querySelector(".weather").style.display = "none";
startProgressBar();
await checkWeather(searchBox.value);
await checkForecast(searchBox.value);
// Wait for progress bar to complete (500ms for full bar)
await new Promise(resolve => setTimeout(resolve, 500));
displayWeather();
}
searchBtn.addEventListener("click", () => {
performSearch();
});
searchBox.addEventListener("keypress", (event) => {
if (event.key === "Enter") {
performSearch();
}
});
locationBtn.addEventListener("click", () => {
if (navigator.geolocation) {
progressBar.style.display = "flex";
progressBar.style.setProperty('--width', 0);
clearInterval(progressInterval);
weatherData = null;
hasError = false;
document.querySelector(".error").style.display = "none";
document.querySelector(".weather").style.display = "none";
startProgressBar();
navigator.geolocation.getCurrentPosition(async (position) => {
const lat = position.coords.latitude;
const lon = position.coords.longitude;
await checkWeatherByCoords(lat, lon);
await checkForecastByCoords(lat, lon);
// Wait for progress bar to complete (500ms for full bar)
await new Promise(resolve => setTimeout(resolve, 500));
displayWeather();
}, (error) => {
console.error("Error getting location:", error);
hasError = false;
progressBar.style.display = "none";
document.querySelector(".error").style.display = "block";
document.querySelector(".error p").innerHTML = "Unable to access your location. Please enable location services.";
document.querySelector(".weather").style.display = "none";
});
} else {
alert("Geolocation is not supported by your browser");
}
});