Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
369 lines (331 loc) · 14.5 KB
/
Copy pathscript.js
File metadata and controls
369 lines (331 loc) · 14.5 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
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
let cityInput = document.getElementById('city_input'),
searchBtn = document.getElementById('searchBtn'),
locationBtn = document.getElementById('locationBtn'),
api_key = '238cb5938a785d6545fd3c798fcc8bef',
currentWeatherCard = document.querySelector('.weather-left .card'),
fiveDaysForecastCard = document.querySelector('.day-forecast'),
aqiCard = document.querySelectorAll('.highlights .card')[0],
sunriseCard = document.querySelectorAll('.highlights .card')[1],
humidityVal = document.getElementById('humidityVal'),
pressureVal = document.getElementById('pressureVal'),
visibilityVal = document.getElementById('visibilityVal'),
windSpeedVal = document.getElementById('windSpeedVal'),
feelsVal = document.getElementById('feelsVal');
hourlyForecastCard =document.querySelector('.hourly-forecast'),
// Check if elements exist
console.log('Elements found:', {
cityInput: !!cityInput,
searchBtn: !!searchBtn,
currentWeatherCard: !!currentWeatherCard,
fiveDaysForecastCard: !!fiveDaysForecastCard,
aqiCard: !!aqiCard,
sunriseCard: !!sunriseCard,
humidityVal: !!humidityVal,
pressureVal: !!pressureVal,
visibilityVal: !!visibilityVal,
windSpeedVal: !!windSpeedVal,
feelsVal: !!feelsVal
});
let aqiList = ['Good', 'Fair', 'Moderate', 'Poor', 'Very Poor'];
// Safe element update function
function safeUpdate(element, content) {
if (element) {
element.innerHTML = content;
} else {
console.warn('Element not found:', element);
}
}
function showLoading() {
safeUpdate(currentWeatherCard, '<p>Loading...</p>');
safeUpdate(fiveDaysForecastCard, '<p>Loading forecast...</p>');
safeUpdate(aqiCard, '<p>Loading air quality...</p>');
if (sunriseCard) {
sunriseCard.innerHTML = '<p>Loading...</p>';
}
}
function getWeatherDetails(name, lat, lon, country, state) {
showLoading();
let FORECAST_API_URL = `https://api.openweathermap.org/data/2.5/forecast?lat=${lat}&lon=${lon}&appid=${api_key}&units=metric`,
WEATHER_API_URL = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${api_key}&units=metric`,
AIR_POLLUTION_API_URL = `https://api.openweathermap.org/data/2.5/air_pollution?lat=${lat}&lon=${lon}&appid=${api_key}&units=metric`;
const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
// Fetch current weather
fetch(WEATHER_API_URL)
.then(res => {
console.log('Weather API Response status:', res.status);
if (!res.ok) {
throw new Error(`Weather API failed: ${res.status} ${res.statusText}`);
}
return res.json();
})
.then(data => {
console.log('Weather data received:', data);
if (!data || typeof data !== 'object') {
throw new Error('Invalid weather data received');
}
let date = new Date();
// Safely extract data with fallbacks
const temp = data.main?.temp ? data.main.temp.toFixed(1) : '--';
const description = data.weather?.[0]?.description || '--';
const icon = data.weather?.[0]?.icon || '01d';
safeUpdate(currentWeatherCard, `
<div class="current-weather">
<div class="details">
<p>Now</p>
<h2>${temp}°C</h2>
<p>${description}</p>
</div>
<div class="weather-icon">
<img src="https://openweathermap.org/img/wn/${icon}@2x.png" alt="weather icon">
</div>
</div>
<hr>
<div class="card-footer">
<p><i class="fa-light fa-calendar"></i>${days[date.getDay()]}, ${date.getDate()} ${months[date.getMonth()]}</p>
<p><i class="fa-light fa-location-dot"></i>${name}, ${country}</p>
</div>
`);
// Extract weather details safely
let sunrise = data.sys?.sunrise || 0;
let sunset = data.sys?.sunset || 0;
let timezone = data.timezone || 0;
let visibility = data.visibility || 0;
let humidity = data.main?.humidity ?? "--";
let pressure = data.main?.pressure ?? "--";
let feels_like = data.main?.feels_like ?? "--";
let speed = data.wind?.speed ?? "--";
// Format times safely
let sRiseTime = '--';
let sSetTime = '--';
try {
if (sunrise && sunset) {
sRiseTime = moment.unix(sunrise).utcOffset(timezone / 60).format('hh:mm A');
sSetTime = moment.unix(sunset).utcOffset(timezone / 60).format('hh:mm A');
}
} catch (error) {
console.error('Error formatting sunrise/sunset times:', error);
}
// Update sunrise card only if it exists
if (sunriseCard) {
sunriseCard.innerHTML = `
<div class="card-head">
<p>Sunrise & Sunset</p>
</div>
<div class="sunrise-sunset">
<div class="item">
<div class="icon">
<i class="fa-light fa-sunrise fa-4x"></i>
</div>
<div>
<p>Sunrise</p>
<h2>${sRiseTime}</h2>
</div>
</div>
<div class="item">
<div class="icon">
<i class="fa-light fa-sunset fa-4x"></i>
</div>
<div>
<p>Sunset</p>
<h2>${sSetTime}</h2>
</div>
</div>
</div>
`;
}
// Update other values safely
if (humidityVal) humidityVal.innerHTML = `${humidity}${humidity !== "--" ? "%" : ""}`;
if (pressureVal) pressureVal.innerHTML = `${pressure !== "--" ? pressure + " hPa" : "--"}`;
if (visibilityVal) visibilityVal.innerHTML = `${visibility ? (visibility / 1000).toFixed(1) + " km" : "--"}`;
if (windSpeedVal) windSpeedVal.innerHTML = `${speed !== "--" ? speed + " m/s" : "--"}`;
if (feelsVal) feelsVal.innerHTML = `${feels_like !== "--" ? Number(feels_like).toFixed(1) + "°C" : "--"}`;
})
.catch((error) => {
console.error('Failed to fetch current weather:', error);
safeUpdate(currentWeatherCard, '<p>Error loading weather data</p>');
});
// Fetch Air Quality Index
fetch(AIR_POLLUTION_API_URL)
.then(res => res.json())
.then(data => {
if (!data || !data.list || data.list.length === 0) {
console.error('Invalid air quality data');
safeUpdate(aqiCard, '<p>Air quality data not available</p>');
return;
}
const components = data.list[0].components;
// Safe value extraction function - FIXED CODE
const getSafeValue = (value) => {
if (value === null || value === undefined) return '--';
const numValue = Number(value);
if (isNaN(numValue) || !isFinite(numValue)) return '--';
// Filter out unreasonably large values
if (Math.abs(numValue) > 1000) return '--';
return numValue.toFixed(2);
};
const pm2_5 = getSafeValue(components.pm2_5);
const pm10 = getSafeValue(components.pm10);
const so2 = getSafeValue(components.so2);
const co = getSafeValue(components.co);
const no = getSafeValue(components.no);
const no2 = getSafeValue(components.no2);
const nh3 = getSafeValue(components.nh3);
const o3 = getSafeValue(components.o3);
const aqi = data.list[0].main.aqi || 1;
safeUpdate(aqiCard, `
<div class="card-head">
<p>Air Quality Index</p>
<p class="air-index aqi-${aqi}">${aqiList[aqi - 1] || 'Unknown'}</p>
</div>
<div class="air-indices">
<i class="fa-regular fa-wind fa-3x"></i>
<div class="item">
<p>PM2.5</p>
<h2>${pm2_5}</h2>
</div>
<div class="item">
<p>PM10</p>
<h2>${pm10}</h2>
</div>
<div class="item">
<p>SO2</p>
<h2>${so2}</h2>
</div>
<div class="item">
<p>CO</p>
<h2>${co}</h2>
</div>
<div class="item">
<p>NO</p>
<h2>${no}</h2>
</div>
<div class="item">
<p>NO2</p>
<h2>${no2}</h2>
</div>
<div class="item">
<p>NH3</p>
<h2>${nh3}</h2>
</div>
<div class="item">
<p>O3</p>
<h2>${o3}</h2>
</div>
</div>
`);
})
.catch((error) => {
console.error('Failed to fetch Air Quality Index:', error);
safeUpdate(aqiCard, '<p>Failed to load air quality data</p>');
});
// Fetch 5-day forecast
fetch(FORECAST_API_URL)
.then(res => {
if (!res.ok) {
throw new Error('Forecast API response not OK');
}
return res.json();
})
.then(data => {
if (!data || !data.list) {
throw new Error('Invalid forecast data');
}
let hourlyForecast = data.list;
hourlyForecastCard.innerHTML='';
for (let i=0;i<=7;i++){
let hourlyForecastDate=new Date(hourlyForecast[i].dt_txt);
let hr = hourlyForecastDate.getHours();
let a ='PM';
if(hr<12) a = 'AM';
if (hr==0) hr=12;
if(hr>12) hr = hr-12;
hourlyForecastCard.innerHTML+=`
<div class="card">
<p>${hr} ${a}</p>
<img src="https://openweathermap.org/img/wn/${hourlyForecast[i].weather[0].icon}.png" alt="">
<p>${hourlyForecast[i].main.temp.toFixed(1)}°C</p>
</div>
`;
}
let uniqueForecastDays = [];
let fiveDaysForecast = data.list.filter(forecast => {
let forecastDate = new Date(forecast.dt_txt).getDate();
if (!uniqueForecastDays.includes(forecastDate)) {
return uniqueForecastDays.push(forecastDate);
}
});
let forecastHTML = '';
for (let i = 0; i < fiveDaysForecast.length; i++) {
let date = new Date(fiveDaysForecast[i].dt_txt);
const temp = fiveDaysForecast[i].main?.temp ? fiveDaysForecast[i].main.temp.toFixed(1) : '--';
const icon = fiveDaysForecast[i].weather?.[0]?.icon || '01d';
forecastHTML += `
<div class="forecast-item">
<div class="icon-wrapper">
<img src="https://openweathermap.org/img/wn/${icon}.png" alt="">
<span>${temp}°C</span>
</div>
<p>${date.getDate()} ${months[date.getMonth()]}</p>
<p>${days[date.getDay()]}</p>
</div>
`;
}
safeUpdate(fiveDaysForecastCard, forecastHTML);
})
.catch((error) => {
console.error('Failed to fetch weather forecast:', error);
safeUpdate(fiveDaysForecastCard, '<p>Error loading forecast</p>');
});
}
function getCityCoordinates() {
let cityName = cityInput.value.trim();
if (!cityName) {
alert('Please enter a city name');
return;
}
let GEOCODING_API_URL = `https://api.openweathermap.org/geo/1.0/direct?q=${cityName}&limit=1&appid=${api_key}`;
fetch(GEOCODING_API_URL)
.then(res => {
if (!res.ok) {
throw new Error('Geocoding API response not OK');
}
return res.json();
})
.then(data => {
if (!data || data.length === 0) {
alert(`No results found for "${cityName}"`);
return;
}
let { name, lat, lon, country, state } = data[0];
getWeatherDetails(name, lat, lon, country, state);
})
.catch((error) => {
console.error(`Failed to fetch coordinates of ${cityName}:`, error);
alert(`Failed to fetch coordinates of "${cityName}". Please check your internet connection.`);
});
}
function getUserCoordinates(){
navigator.geolocation.getCurrentPosition(position =>{
let {latitude,longitude}=position.coords;
let REVERSE_GEOCODING_URL = `https://api.openweathermap.org/geo/1.0/reverse?lat=${latitude}&lon=${longitude}&limit=1&appid=${api_key}`;
fetch(REVERSE_GEOCODING_URL).then(res =>res.json()).then(data =>{
let {name,country,state}=data[0];
getWeatherDetails(name,latitude,longitude,country,state);
}).catch(()=>{
alert("Failed to Fetch User Coordinates..")
})
})
}
searchBtn.addEventListener('click', getCityCoordinates);
locationBtn.addEventListener('click',getUserCoordinates);
// Allow searching by pressing Enter key
cityInput.addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
getCityCoordinates();
}
});
// Check if moment.js is available
if (typeof moment === 'undefined') {
console.error('Moment.js is not loaded. Please include moment.js in your HTML');
}