-
Notifications
You must be signed in to change notification settings - Fork 19
/
index.js
736 lines (650 loc) · 23.8 KB
/
index.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
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
const apiKey = "91181b4ccb7f36e6b27aefa8bb9b5624";
const searchBtn = document.getElementById("search-btn");
const cityInput = document.getElementById("city-input");
const dateTime = document.getElementById("current-date");
const suggestionsBox = document.getElementById("suggestions");
const suggestions = document.getElementsByClassName("suggestion");
const loadingIndicator = document.getElementById("loading");
const errorMessage = document.getElementById("error-message");
const currentLocationBtn = document.getElementById("current-location-btn");
let forecastInfo = [];
let debounceTimeout;
// Add this to index.js
function showHealthImpact() {
const weatherData = JSON.parse(sessionStorage.getItem("weatherData"));
const aqiData = JSON.parse(sessionStorage.getItem("aqiData"));
function getHealthAdvice(weather, aqi) {
let advice = [];
const temp = weather.main.temp;
const humidity = weather.main.humidity;
const windSpeed = weather.wind.speed;
const aqiValue = aqi.list[0].main.aqi;
const weatherCondition = weather.weather[0].main.toLowerCase();
// Temperature-related advice
if (temp > 35) {
advice.push('Extreme heat! Stay indoors, drink plenty of water, and avoid strenuous activities.');
} else if (temp > 30) {
advice.push('High risk of dehydration. Drink plenty of water and seek shade when outdoors.');
} else if (temp < 0) {
advice.push('Freezing temperatures. Bundle up and protect extremities from frostbite.');
} else if (temp < 10) {
advice.push('Cold weather. Dress in layers and stay warm to prevent hypothermia.');
}
// Humidity-related advice
if (humidity > 70) {
advice.push('High humidity may cause respiratory discomfort and increase risk of heat exhaustion.');
} else if (humidity < 30) {
advice.push('Low humidity can cause dry skin and respiratory irritation. Use a humidifier if indoors.');
}
// Wind-related advice
if (windSpeed > 20) {
advice.push('Strong winds. Be cautious of flying debris and secure loose outdoor items.');
}
// Air quality advice
if (aqiValue > 4) {
advice.push('Very poor air quality. Limit outdoor activities and wear a mask if going outside.');
} else if (aqiValue > 3) {
advice.push('Poor air quality. Consider wearing a mask outdoors, especially if you have respiratory issues.');
} else if (aqiValue > 2) {
advice.push('Moderate air quality. Sensitive groups should consider reducing prolonged outdoor exertion.');
}
// Weather condition specific advice
switch (weatherCondition) {
case 'rain':
advice.push('Rainy conditions. Use caution when driving and carry an umbrella.');
break;
case 'snow':
advice.push('Snowy conditions. Dress warmly, wear appropriate footwear, and be cautious of icy surfaces.');
break;
case 'thunderstorm':
advice.push('Thunderstorm alert. Stay indoors and avoid using electrical appliances.');
break;
case 'fog':
advice.push('Foggy conditions. Use caution when driving and use low beam headlights.');
break;
}
// UV index advice (if available)
if (weather.uvi) {
const uvIndex = weather.uvi;
if (uvIndex > 10) {
advice.push('Extreme UV levels. Avoid sun exposure and wear protective clothing if outdoors.');
} else if (uvIndex > 7) {
advice.push('Very high UV levels. Use strong sun protection and limit mid-day sun exposure.');
} else if (uvIndex > 5) {
advice.push('High UV levels. Wear sunscreen and protective clothing when outdoors.');
}
}
return advice;
}
const healthContainer = document.getElementById('health-impact');
const healthAdvice = getHealthAdvice(weatherData, aqiData);
healthContainer.innerHTML = `
<div class="health-card">
<h3><i class="fas fa-heartbeat"></i> Health Advisory</h3>
<ul>
${healthAdvice.map(advice => `<li>${advice}</li>`).join('')}
</ul>
</div>
`;
// Add a note if no specific advice is given
if (healthAdvice.length === 0) {
healthContainer.innerHTML += `
<p class="no-advice">No specific health advisories for current conditions. Enjoy your day!</p>
`;
}
}
function getUVIndex(lat, lon) {
const uvUrl = `https://api.openweathermap.org/data/2.5/uvi?lat=${lat}&lon=${lon}&appid=${apiKey}`;
return fetch(uvUrl)
.then((response) => {
if (!response.ok) throw new Error("UV data not available");
return response.json();
})
.then((data) => {
sessionStorage.setItem("uvData", JSON.stringify(data));
return data;
});
}
function updateUVInfo(data) {
const uvValue = document.getElementById("uv-value");
const uvLevel = document.getElementById("uv-level");
const uvAdvice = document.getElementById("uv-advice");
const uvProgressFill = document.getElementById("uv-progress-fill");
const uvIndex = data.value;
const uvLevels = {
low: {
range: [0, 2],
level: "Low",
advice: "No protection required. You can safely stay outside.",
color: "uv-low",
},
moderate: {
range: [3, 5],
level: "Moderate",
advice:
"Seek shade during midday hours. Wear sunscreen and protective clothing.",
color: "uv-moderate",
},
high: {
range: [6, 7],
level: "High",
advice:
"Reduce time in the sun between 10 a.m. and 4 p.m. Wear protective clothing and sunscreen.",
color: "uv-high",
},
veryHigh: {
range: [8, 10],
level: "Very High",
advice:
"Minimize sun exposure during midday hours. Protective measures are essential.",
color: "uv-very-high",
},
extreme: {
range: [11, 20],
level: "Extreme",
advice:
"Avoid sun exposure during midday hours. Shirt, sunscreen, and hat are essential.",
color: "uv-extreme",
},
};
let uvCategory;
if (uvIndex <= 2) uvCategory = uvLevels.low;
else if (uvIndex <= 5) uvCategory = uvLevels.moderate;
else if (uvIndex <= 7) uvCategory = uvLevels.high;
else if (uvIndex <= 10) uvCategory = uvLevels.veryHigh;
else uvCategory = uvLevels.extreme;
uvValue.textContent = `UV Index: ${uvIndex}`;
uvLevel.textContent = `Level: ${uvCategory.level}`;
uvAdvice.textContent = uvCategory.advice;
// Update progress bar
uvProgressFill.className = uvCategory.color;
uvProgressFill.style.width = `${(uvIndex / 11) * 100}%`;
}
function getAirQuality(lat, lon) {
const aqiUrl = `https://api.openweathermap.org/data/2.5/air_pollution?lat=${lat}&lon=${lon}&appid=${apiKey}`;
return fetch(aqiUrl)
.then((response) => {
if (!response.ok) throw new Error("Air quality data not available");
return response.json();
})
.then((data) => {
sessionStorage.setItem("aqiData", JSON.stringify(data));
return data;
});
}
function updateAQIInfo(data) {
if (!data || !data.list || !data.list[0]) {
console.error("Invalid AQI data:", data);
return;
}
const aqiValue = document.getElementById("aqi-value");
const aqiStatus = document.getElementById("aqi-status");
const aqiDescription = document.getElementById("aqi-description");
const aqiIcon = document.querySelector(".air-quality .fas.fa-lungs");
const airArr = data.list[0].components;
const co = document.getElementById("co");
const no = document.getElementById("no");
const no2 = document.getElementById("no2");
const o3 = document.getElementById("o3");
const so2 = document.getElementById("so2");
const pm2 = document.getElementById("pm2");
const pm10 = document.getElementById("pm10");
const nh3 = document.getElementById("nh3");
co.innerText = `${airArr.co} ppm`;
no.innerText = `${airArr.no} µg`;
no2.innerText = `${airArr.no2} ppb`;
o3.innerText = `${airArr.o3} µg`;
so2.innerText = `${airArr.so2} ppb`;
pm2.innerText = `${airArr.pm2_5} µg`;
pm10.innerText = `${airArr.pm10} µg`;
nh3.innerText = `${airArr.nh3} µg`;
const aqi = data.list[0].main.aqi;
const aqiStatuses = {
1: {
status: "Good",
description:
"Air quality is satisfactory, and air pollution poses little or no risk.",
},
2: {
status: "Fair",
description:
"Air quality is acceptable; however, some pollutants may be moderate.",
},
3: {
status: "Moderate",
description: "Members of sensitive groups may experience health effects.",
},
4: {
status: "Poor",
description: "Everyone may begin to experience health effects.",
},
5: {
status: "Very Poor",
description:
"Health warnings of emergency conditions. Everyone is more likely to be affected.",
},
};
const aqiInfo = aqiStatuses[aqi];
if (aqiValue) aqiValue.textContent = `AQI: ${aqi}`;
if (aqiStatus) aqiStatus.textContent = `Quality: ${aqiInfo.status}`;
if (aqiDescription) aqiDescription.textContent = aqiInfo.description;
if (aqiIcon) aqiIcon.style.color = getAQIColor(aqi);
}
// Get current location button handler
function handleGetCurrentLocation() {
if (navigator.geolocation) {
showLoading();
navigator.geolocation.getCurrentPosition(
// Success callback
(position) => {
const { latitude, longitude } = position.coords;
getWeatherByCurrentLocation(latitude, longitude);
},
// Error callback
(error) => {
hideLoading();
handleLocationError(error);
},
// Options
{
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0,
}
);
} else {
displayErrorMessage("Geolocation is not supported by your browser");
}
}
// Handle location errors
function handleLocationError(error) {
let errorMessage;
switch (error.code) {
case error.PERMISSION_DENIED:
errorMessage = "Please allow location access to use this feature.";
break;
case error.POSITION_UNAVAILABLE:
errorMessage = "Location information is unavailable.";
break;
case error.TIMEOUT:
errorMessage = "Location request timed out.";
break;
default:
errorMessage = "An unknown error occurred getting your location.";
}
displayErrorMessage(errorMessage);
}
function getAQIColor(aqi) {
const colors = {
1: "#00e400", // Good - Green
2: "#ffff00", // Fair - Yellow
3: "#ff7e00", // Moderate - Orange
4: "#ff0000", // Poor - Red
5: "#7f0023", // Very Poor - Purple
};
return colors[aqi] || "#cccccc";
}
// Get weather for current location
function getWeatherByCurrentLocation(lat, lon) {
const weatherUrl = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&units=metric&appid=${apiKey}`;
const forecastUrl = `https://api.openweathermap.org/data/2.5/forecast?lat=${lat}&lon=${lon}&units=metric&appid=${apiKey}`;
const aqiUrl = `https://api.openweathermap.org/data/2.5/air_pollution?lat=${lat}&lon=${lon}&appid=${apiKey}`;
const uvUrl = `https://api.openweathermap.org/data/2.5/uvi?lat=${lat}&lon=${lon}&appid=${apiKey}`;
sessionStorage.setItem("currPos", JSON.stringify({ lat, lon }));
Promise.all([
fetch(weatherUrl).then((response) => response.json()),
fetch(forecastUrl).then((response) => response.json()),
fetch(aqiUrl).then((response) => response.json()),
fetch(uvUrl).then((response) => response.json()),
])
.then(([weatherData, forecastData, aqiData, uvData]) => {
sessionStorage.setItem("weatherData", JSON.stringify(weatherData));
sessionStorage.setItem("forecastData", JSON.stringify(forecastData));
sessionStorage.setItem("aqiData", JSON.stringify(aqiData));
sessionStorage.setItem("uvData", JSON.stringify(uvData));
hideLoading();
window.location = "weather_info.html";
})
.catch((error) => {
console.error("Error:", error);
displayErrorMessage("Unable to fetch weather data. Please try again.");
hideLoading();
});
}
if (currentLocationBtn) {
currentLocationBtn.addEventListener("click", handleGetCurrentLocation);
}
function showLoading() {
loadingIndicator.style.display = "block";
}
function hideLoading() {
loadingIndicator.style.display = "none";
}
function displayErrorMessage(message) {
errorMessage.textContent = message;
errorMessage.style.display = "block"; // Show the error message
}
function hideErrorMessage() {
errorMessage.style.display = "none"; // Hide the error message
}
let selectedSuggestionIndex = -1;
if (cityInput) {
cityInput.addEventListener("input", async function () {
const query = cityInput.value.trim();
clearTimeout(debounceTimeout);
selectedSuggestionIndex = -1;
debounceTimeout = setTimeout(async () => {
if (query.length > 0) {
const suggestions = await fetchCities(query);
displaySuggestions(suggestions);
} else {
suggestionsBox.innerHTML = "";
}
}, 400);
});
cityInput.addEventListener("keydown", (e) => {
const suggestionItems = Array.from(suggestionsBox.children);
if (e.key === "ArrowDown") {
e.preventDefault();
if (selectedSuggestionIndex < suggestionItems.length - 1) {
selectedSuggestionIndex++;
} else {
selectedSuggestionIndex = 0; //when user at last item and press down key it will go to first item
}
updateSuggestionHighlight(suggestionItems);
} else if (e.key === "ArrowUp") {
e.preventDefault();
if (selectedSuggestionIndex > 0) {
selectedSuggestionIndex--;
} else {
selectedSuggestionIndex = suggestionItems.length - 1; //when user at first item and press up key it will go to last item
}
updateSuggestionHighlight(suggestionItems);
} else if (e.key === "Enter" && selectedSuggestionIndex >= 0) {
e.preventDefault();
cityInput.value = suggestionItems[selectedSuggestionIndex].textContent;
suggestionsBox.innerHTML = "";
selectedSuggestionIndex = -1;
}
});
}
async function fetchCities(query) {
console.log("api called");
const response = await fetch(
`https://api.openweathermap.org/geo/1.0/direct?q=${query}&limit=5&appid=${apiKey}`
);
const cities = await response.json();
return cities.map((city) => `${city.name}, ${city.country}`);
}
function displaySuggestions(suggestions) {
suggestionsBox.innerHTML = "";
suggestions.forEach((suggestion) => {
const li = document.createElement("li");
li.classList.add("suggestion");
li.textContent = suggestion;
suggestionsBox.appendChild(li);
li.addEventListener("click", function () {
cityInput.value = suggestion;
suggestionsBox.innerHTML = "";
selectedSuggestionIndex = -1;
});
});
}
function updateSuggestionHighlight(suggestionItems) {
//for visual effect of suggestion selection
suggestionItems.forEach((item, index) => {
if (index === selectedSuggestionIndex) {
item.style.backgroundColor = "#f0f0f0";
item.style.boxShadow = "0 0 15px rgba(0, 0, 0, 0.2)";
item.style.transform = "translateY(-2px)";
cityInput.value = item.textContent;
} else {
item.style.backgroundColor = "rgba(255, 255, 255, 0.7)";
item.style.boxShadow = "";
item.style.transform = "translateY(0)";
}
});
}
const fetchData = () => {
const city = cityInput.value.trim();
if (city !== "") {
showLoading();
getWeatherByCity(city)
.then(() => {
//console.log("Fetching weather data for:", city);
return getForecastByCity(city);
})
.then(() => {
hideLoading();
})
.catch((error) => {
console.error("Error in weather/fetch: ", error);
hideLoading();
});
} else {
displayErrorMessage("Please enter a city name.");
}
};
if (searchBtn) {
searchBtn.addEventListener("click", fetchData);
}
if (cityInput) {
cityInput.addEventListener("keyup", (e) => {
if (e.key === "Enter") {
fetchData();
}
});
}
function getWeatherByCity(city) {
const apiUrl = `https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${apiKey}`;
let latitude, longitude;
return fetch(apiUrl)
.then((response) => {
if (!response.ok) {
throw new Error("City not found");
}
return response.json();
})
.then((data) => {
sessionStorage.setItem("weatherData", JSON.stringify(data));
// Store coordinates for subsequent API calls
latitude = data.coord.lat;
longitude = data.coord.lon;
sessionStorage.setItem(
"currPos",
JSON.stringify({ lat: latitude, lon: longitude })
);
const sunrise = new Date(data.sys.sunrise * 1000).toLocaleTimeString();
const sunset = new Date(data.sys.sunset * 1000).toLocaleTimeString();
sessionStorage.setItem("sunrise", sunrise);
sessionStorage.setItem("sunset", sunset);
// Create promises for both AQI and UV index data
const aqiPromise = fetch(
`https://api.openweathermap.org/data/2.5/air_pollution?lat=${latitude}&lon=${longitude}&appid=${apiKey}`
);
const uvPromise = fetch(
`https://api.openweathermap.org/data/2.5/uvi?lat=${latitude}&lon=${longitude}&appid=${apiKey}`
);
// Return both promises to be resolved
return Promise.all([aqiPromise, uvPromise]);
})
.then(([aqiResponse, uvResponse]) => {
// Convert both responses to JSON
return Promise.all([aqiResponse.json(), uvResponse.json()]);
})
.then(([aqiData, uvData]) => {
// Store both sets of data in sessionStorage
sessionStorage.setItem("aqiData", JSON.stringify(aqiData));
sessionStorage.setItem("uvData", JSON.stringify(uvData));
hideErrorMessage();
})
.catch((error) => {
displayErrorMessage(`${city} not found. Please try again...`);
cityInput.value = "";
hideLoading();
throw error;
});
}
function getForecastByCity(city) {
const apiUrl2 = `https://api.openweathermap.org/data/2.5/forecast?q=${city}&units=metric&appid=${apiKey}`;
return fetch(apiUrl2)
.then((response) => {
if (!response.ok) {
throw new Error("City not found");
}
return response.json();
})
.then((data) => {
sessionStorage.setItem("forecastData", JSON.stringify(data));
hideErrorMessage();
hideLoading();
window.location = "weather_info.html";
})
.catch((error) => {
displayErrorMessage(`${city} not found. Please try again...`);
cityInput.value = "";
hideLoading();
throw error;
});
}
window.onload = function () {
const weatherData = JSON.parse(sessionStorage.getItem("weatherData"));
const forecastData = JSON.parse(sessionStorage.getItem("forecastData"));
const aqiData = JSON.parse(sessionStorage.getItem("aqiData"));
const uvData = JSON.parse(sessionStorage.getItem("uvData"));
console.log("Weather Data:", weatherData);
console.log("Forecast Data:", forecastData);
console.log("AQI Data:", aqiData);
if (weatherData) {
updateWeatherInfo(weatherData);
loadWeatherMap();
showHealthImpact();
}
if (forecastData && forecastData.list) {
forecastInfo = forecastData.list.filter((_, i) => i % 8 === 0).slice(0, 5);
populateForecastCards();
}
if (aqiData) {
updateAQIInfo(aqiData);
}
if (uvData) {
updateUVInfo(uvData);
}
};
function degreesToDirection(degrees) {
const directions = ['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW'];
const index = Math.round(degrees / 22.5) % 16;
return directions[index];
}
function updateWindDirection(degrees) {
const windDirectionIcon = document.getElementById('wind-direction-icon');
const windDirectionText = document.getElementById('wind-direction-text');
if (windDirectionIcon && windDirectionText) {
windDirectionIcon.style.transform = `rotate(${degrees}deg)`;
const direction = degreesToDirection(degrees);
windDirectionText.textContent = `${direction} (${degrees}°)`;
}
}
function updateWeatherInfo(data) {
const cityName = document.getElementById("city-name");
const temperature = document.getElementById("temperature");
const weatherDesc = document.getElementById("weather-desc");
const humidity = document.getElementById("humidity");
const windSpeed = document.getElementById("wind-speed");
const sunriseTimes = document.querySelectorAll(".sunrise-time");
const sunsetTimes = document.querySelectorAll(".sunset-time");
const chanceOfRain = document.getElementById("chance-of-rain");
const sunrise = sessionStorage.getItem("sunrise");
const sunset = sessionStorage.getItem("sunset");
cityName.textContent = data.name;
temperature.textContent = `${data.main.temp} °C`;
weatherDesc.textContent = data.weather[0].description;
humidity.textContent = `${data.main.humidity} %`;
windSpeed.textContent = `${data.wind.speed} m/s`;
sunriseTimes.forEach(elem => {
elem.textContent = `${sunrise} A.M.`;
});
sunsetTimes.forEach(elem => {
elem.textContent = `${sunset} P.M.`;
});
updateWindDirection(data.wind.deg);
}
function populateForecastCards() {
const forecastCards = document.querySelectorAll(".forecast-card");
forecastCards.forEach((card, index) => {
const forecast = forecastInfo[index];
const date = new Date(forecast.dt * 1000);
const day = daysOfWeek[date.getDay()];
const temperature = `${Math.round(forecast.main.temp)}°C`;
const weatherDescription = forecast.weather[0].description;
const iconClass = getWeatherIconClass(forecast.weather[0].icon);
const humidityElem = card.querySelector(".humidity");
const windSpeedElem = card.querySelector(".wind-speed");
const iconSrc = getWeatherIconClass(forecast.weather[0].icon);
const mainSrc = getWeatherIconClass(forecast.weather[0].icon);
const dayElem = card.querySelector(".day");
const tempElem = card.querySelector(".temp");
const iconElem = card.querySelector(".icon");
const statusElem = card.querySelector(".status");
const mainElem = document.querySelector(".icons");
const chanceOfRain = document.querySelector("#chance-of-rain");
dayElem.textContent = day;
tempElem.textContent = temperature;
iconElem.src = iconSrc;
mainElem.src = mainSrc;
statusElem.textContent = weatherDescription;
const rainChance = (forecast.pop * 100).toFixed(1);
humidityElem.textContent = `${forecast.main.humidity} %`;
windSpeedElem.textContent = `${forecast.wind.speed} m/s`;
chanceOfRain.textContent = `Chance Of Rain: ${rainChance}%`;
if (iconSrc.endsWith('clear-sky.png')) {
iconElem.classList.add('rotate');
mainElem.classList.add('rotate');
}
else {
iconElem.classList.add('otherImg');
mainElem.classList.add('otherImg');
iconElem.classList.remove('rotate');
mainElem.classList.remove('rotate');
}
});
}
function getWeatherIconClass(icon) {
const iconMapping = {
"01d": "./images/clear-sky.png",
"01n": "./images/clear-sky.png",
"02d": "./images/cloud-sun.png",
"02n": "./images/cloud-sun.png",
"03d": "./images/scatter-clouds.png",
"03n": "./images/scatter-clouds.png",
"04d": "./images/partial-cloud.png",
"04n": "./images/partial-cloud.png",
"09d": "./images/shower-rain.png",
"09n": "./images/shower-rain.png",
"10d": "./images/rainy.png",
"10n": "./images/rainy.png",
"11d": "./images/stormy.png",
"11n": "./images/stormy.png",
"13d": "./images/snow.png",
"13n": "./images/snow.png",
"50d": "./images/mist.png",
"50n": "./images/mist.png",
};
return iconMapping[icon] || "fa-cloud";
}
const currentDate = new Date();
const daysOfWeek = [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
];
const currentDay = daysOfWeek[currentDate.getDay()];
const year = currentDate.getFullYear();
const month = String(currentDate.getMonth() + 1).padStart(2, "0");
const day = String(currentDate.getDate()).padStart(2, "0");
const formattedDate = `${day}-${month}-${year}`;
dateTime.textContent = `${formattedDate} / ${currentDay}`;