Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
126 lines (112 loc) · 3.97 KB
/
Copy pathscript.js
File metadata and controls
126 lines (112 loc) · 3.97 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
const apiKey = '31911f09593786caffacdfe6399231ad';
const form = document.getElementById("searchForm");
const cityInput = document.getElementById("cityInput");
const weatherCard = document.getElementById("weatherCard");
const forecastCard = document.getElementById("forecastCard");
const forecastList = document.getElementById("forecastList");
const cityNameEl = document.getElementById("cityName");
const conditionEl = document.getElementById("condition");
const tempEl = document.getElementById("temp");
const feelsEl = document.getElementById("feelsLike");
const windEl = document.getElementById("wind");
const humidEl = document.getElementById("humid");
form.addEventListener("submit", function (event) {
event.preventDefault();
const city = cityInput.value.trim();
if (city) {
fetchWeatherByCity(city);
}
});
window.addEventListener("load", () => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
(position) => {
const { latitude, longitude } = position.coords;
fetchWeatherByLocation(latitude, longitude);
},
() => {
console.warn('Geolocation permission denied.');
}
);
}
});
async function fetchWeatherByCity(city) {
const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${apiKey}`;
try {
const response = await fetch(url);
const data = await response.json();
if (data.cod === 200) {
updateWeatherCard(data);
fetchForecast(data.coord.lat, data.coord.lon);
applyTheme(data.dt, data.timezone);
} else {
alert('City not found. Please try again.');
}
} catch (error) {
alert('Error fetching weather data.');
console.error(error);
}
}
async function fetchWeatherByLocation(lat, lon) {
const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&units=metric&appid=${apiKey}`;
try {
const response = await fetch(url);
const data = await response.json();
updateWeatherCard(data);
fetchForecast(lat, lon);
applyTheme(data.dt, data.timezone);
} catch (error) {
alert('Error fetching location-based weather.');
console.error(error);
}
}
function updateWeatherCard(data) {
cityNameEl.textContent = data.name;
tempEl.textContent = Math.round(data.main.temp);
feelsEl.textContent = Math.round(data.main.feels_like);
conditionEl.textContent = data.weather[0].description;
windEl.textContent = Math.round(data.wind.speed);
humidEl.textContent = data.main.humidity;
weatherCard.classList.remove("hidden");
}
async function fetchForecast(lat, lon) {
const url = `https://api.openweathermap.org/data/2.5/forecast?lat=${lat}&lon=${lon}&units=metric&appid=${apiKey}`;
try {
const response = await fetch(url);
const data = await response.json();
const daily = {};
data.list.forEach(item => {
const date = item.dt_txt.split(" ")[0];
if (!daily[date]) {
daily[date] = item;
}
});
const dates = Object.keys(daily).slice(1, 4); // Next 3 days
forecastList.innerHTML = '';
dates.forEach(date => {
const item = daily[date];
const day = new Date(item.dt_txt).toLocaleDateString(undefined, { weekday: 'short' });
const html = `
<div>
<p class="label">${day}</p>
<p>${Math.round(item.main.temp)}°C</p>
<p>${item.weather[0].description}</p>
</div>
`;
forecastList.innerHTML += html;
});
forecastCard.classList.remove("hidden");
} catch (error) {
console.error("Forecast fetch failed", error);
}
}
function applyTheme(timestamp, timezoneOffset) {
const localTime = new Date((timestamp + timezoneOffset) * 1000);
const hour = localTime.getUTCHours();
document.body.classList.remove("day", "night");
if (hour >= 6 && hour < 18) {
document.body.classList.add("day");
} else {
document.body.classList.add("night");
}
}