Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
523 lines (432 loc) · 18.3 KB
/
Copy pathscript.js
File metadata and controls
523 lines (432 loc) · 18.3 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
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
const searchInput = document.getElementById('search-input');
const searchBtn = document.getElementById('search-btn');
const themeToggle = document.getElementById('theme-toggle');
const locationBtn = document.getElementById('location-btn');
const favoritesList = document.getElementById('favorites-list');
const locationName = document.getElementById('location-name');
const currentDate = document.getElementById('current-date');
const weatherIcon = document.getElementById('weather-icon');
const currentTemp = document.getElementById('current-temp');
const feelsLike = document.getElementById('feels-like');
const weatherCondition = document.getElementById('weather-condition');
const humidity = document.getElementById('humidity');
const windSpeed = document.getElementById('wind-speed');
const pressure = document.getElementById('pressure');
const sunriseTime = document.getElementById('sunrise-time');
const sunsetTime = document.getElementById('sunset-time');
const visibility = document.getElementById('visibility');
const cloudCover = document.getElementById('cloud-cover');
const hourlyForecast = document.getElementById('hourly-forecast');
const dailyForecast = document.getElementById('daily-forecast');
const tabBtns = document.querySelectorAll('.tab-btn');
let currentLocation = { lat: 24.374, lon: 88.6011, asl: 23 };
let favorites = JSON.parse(localStorage.getItem('weatherly-favorites')) || [];
document.addEventListener('DOMContentLoaded', () => {
loadTheme();
loadFavorites();
getCurrentLocation();
searchBtn.addEventListener('click', handleSearch);
searchInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') handleSearch();
});
themeToggle.addEventListener('click', toggleTheme);
locationBtn.addEventListener('click', getCurrentLocation);
tabBtns.forEach(btn => {
btn.addEventListener('click', () => {
tabBtns.forEach(b => b.classList.remove('active'));
btn.classList.add('active');
const tabId = btn.getAttribute('data-tab');
document.querySelectorAll('.tab-pane').forEach(pane => {
pane.classList.remove('active');
});
document.getElementById(tabId).classList.add('active');
});
});
});
function getCurrentLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
(position) => {
// Get elevation data (approximate)
getElevation(position.coords.latitude, position.coords.longitude)
.then(asl => {
currentLocation = {
lat: position.coords.latitude,
lon: position.coords.longitude,
asl: asl
};
fetchWeatherData();
})
.catch(() => {
// Fallback with approximate elevation
currentLocation = {
lat: position.coords.latitude,
lon: position.coords.longitude,
asl: Math.round(position.coords.altitude || 100)
};
fetchWeatherData();
});
},
(error) => {
console.error("Error getting location:", error);
// Fallback to default location
fetchWeatherData();
}
);
} else {
alert("Geolocation is not supported by this browser.");
fetchWeatherData();
}
}
// Get elevation for coordinates (simple approximation)
async function getElevation(lat, lon) {
// In a real app, you would use an elevation API
// For now, we'll use a simple approximation based on latitude
// This is just a placeholder - replace with actual elevation API in production
try {
// Rough approximation: sea level near coasts, higher inland
// This is very simplified and not accurate
const elevation = Math.max(0, Math.round(100 + Math.abs(lat) * 10));
return elevation;
} catch (error) {
console.error("Error getting elevation:", error);
return 100; // Default fallback
}
}
// Handle search functionality
async function handleSearch() {
const query = searchInput.value.trim();
if (!query) return;
try {
// Use a geocoding service to convert city name to coordinates
// For this example, we'll use Nominatim (OpenStreetMap)
const response = await fetch(`https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(query)}&limit=1`);
const data = await response.json();
if (data.length === 0) {
alert('Location not found. Please try another search.');
return;
}
const lat = parseFloat(data[0].lat);
const lon = parseFloat(data[0].lon);
// Get elevation
const asl = await getElevation(lat, lon);
currentLocation = {
lat: lat,
lon: lon,
asl: asl,
name: data[0].display_name
};
fetchWeatherData();
searchInput.value = '';
} catch (error) {
console.error('Error searching location:', error);
showError('Failed to search location. Please try again.');
}
}
/* async function fetchWeatherData() {
try {
showLoading();
const url = `${API_BASE_URL}?apikey=${API_KEY}&lat=${currentLocation.lat}&lon=${currentLocation.lon}&asl=${currentLocation.asl}&format=json`;
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
displayWeatherData(data);
} catch (error) {
console.error('Error fetching weather data:', error);
showError('Failed to fetch weather data. Please try again later.');
}
} */
async function fetchWeatherData() {
try {
showLoading();
const url = `/api/weather?lat=${currentLocation.lat}&lon=${currentLocation.lon}&asl=${currentLocation.asl}`;
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
displayWeatherData(data);
console.log(data);
// use your weather data...
} catch (error) {
console.error('Error fetching weather data:', error);
showError('Failed to fetch weather data. Please try again later.');
}
}
// Display weather data in UI
function displayWeatherData(data) {
// Set location name
const locationDisplayName = currentLocation.name || `${data.geometry.coordinates[1].toFixed(4)}, ${data.geometry.coordinates[0].toFixed(4)}`;
locationName.textContent = locationDisplayName;
// Set current date
const now = new Date();
const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
currentDate.textContent = now.toLocaleDateString(undefined, options);
// Get current weather from the first hour of data
const currentHourIndex = 0;
const currentData = data.data_1h;
if (!currentData || !currentData.temperature || currentData.temperature.length === 0) {
showError('Weather data not available');
return;
}
// Current temperature
const currentTempValue = currentData.temperature[currentHourIndex];
currentTemp.textContent = `${Math.round(currentTempValue)}°`;
// "Feels like" temperature (using temperature + wind chill effect approximation)
let feelsLikeValue = currentTempValue;
if (currentData.windspeed && currentData.windspeed.length > currentHourIndex) {
const windSpeedVal = currentData.windspeed[currentHourIndex];
// Simple wind chill approximation
if (windSpeedVal > 5 && currentTempValue < 10) {
feelsLikeValue = Math.round(currentTempValue - (windSpeedVal * 0.2));
}
}
feelsLike.textContent = `Feels like ${Math.round(feelsLikeValue)}°`;
// Weather condition based on precipitation and clouds
let condition = "Clear sky";
let iconCode = "01d"; // Default sunny icon
if (currentData.precipitation && currentData.precipitation.length > currentHourIndex) {
const precipitation = currentData.precipitation[currentHourIndex];
if (precipitation > 0.5) {
condition = "Rain";
iconCode = "10d";
} else if (precipitation > 0) {
condition = "Light rain";
iconCode = "09d";
}
}
// Check clouds
if (currentData.cloudcover && currentData.cloudcover.length > currentHourIndex) {
const cloudCoverVal = currentData.cloudcover[currentHourIndex];
if (cloudCoverVal > 80) {
if (condition === "Clear sky") {
condition = "Overcast";
iconCode = "04d";
}
} else if (cloudCoverVal > 50) {
if (condition === "Clear sky") {
condition = "Partly cloudy";
iconCode = "03d";
}
} else if (cloudCoverVal > 20) {
if (condition === "Clear sky") {
condition = "Few clouds";
iconCode = "02d";
}
}
}
// Check if it's night time
const hour = now.getHours();
if (hour < 6 || hour > 18) {
iconCode = iconCode.replace('d', 'n');
}
weatherCondition.textContent = condition;
// Weather icon (using OpenWeatherMap icons for consistency with CSS)
weatherIcon.src = `https://openweathermap.org/img/wn/${iconCode}@2x.png`;
weatherIcon.alt = condition;
// Additional weather info
if (currentData.relativehumidity && currentData.relativehumidity.length > currentHourIndex) {
humidity.textContent = `${Math.round(currentData.relativehumidity[currentHourIndex])}%`;
}
if (currentData.windspeed && currentData.windspeed.length > currentHourIndex) {
windSpeed.textContent = `${Math.round(currentData.windspeed[currentHourIndex])} km/h`;
}
// Pressure - meteoblue doesn't provide this in basic package, so we'll use a standard value
pressure.textContent = "1013 hPa";
// Sunrise/sunset - meteoblue doesn't provide in basic package
// We'll calculate approximate times
const today = new Date();
const sunriseDate = new Date(today);
sunriseDate.setHours(6, 0, 0); // Approx 6 AM
const sunsetDate = new Date(today);
sunsetDate.setHours(18, 0, 0); // Approx 6 PM
sunriseTime.textContent = sunriseDate.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
sunsetTime.textContent = sunsetDate.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
// Visibility - meteoblue doesn't provide in basic package
visibility.textContent = "10.0 km";
// Cloud cover
if (currentData.cloudcover && currentData.cloudcover.length > currentHourIndex) {
cloudCover.textContent = `${Math.round(currentData.cloudcover[currentHourIndex])}%`;
}
// Display forecasts
displayHourlyForecast(data);
displayDailyForecast(data);
// Add to favorites if not already there
addToFavoritesIfNeeded(locationDisplayName, currentLocation.lat, currentLocation.lon);
}
// Display hourly forecast
function displayHourlyForecast(data) {
hourlyForecast.innerHTML = '';
const hourlyData = data.data_1h;
if (!hourlyData || !hourlyData.temperature || hourlyData.temperature.length === 0) {
hourlyForecast.innerHTML = '<p>No hourly data available</p>';
return;
}
// Show next 24 hours (every 3 hours to limit items)
for (let i = 0; i < Math.min(24, hourlyData.temperature.length); i += 3) {
const hourElement = document.createElement('div');
hourElement.className = 'hourly-item';
// Calculate time for this forecast
const forecastTime = new Date();
forecastTime.setHours(forecastTime.getHours() + i);
const timeString = forecastTime.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
// Get temperature
const temp = Math.round(hourlyData.temperature[i]);
// Determine weather condition and icon
let iconCode = "01d";
if (hourlyData.precipitation && hourlyData.precipitation[i] > 0.5) {
iconCode = "10d";
} else if (hourlyData.cloudcover && hourlyData.cloudcover[i] > 80) {
iconCode = "04d";
} else if (hourlyData.cloudcover && hourlyData.cloudcover[i] > 50) {
iconCode = "03d";
} else if (hourlyData.cloudcover && hourlyData.cloudcover[i] > 20) {
iconCode = "02d";
}
// Adjust for night
const hour = forecastTime.getHours();
if (hour < 6 || hour > 18) {
iconCode = iconCode.replace('d', 'n');
}
hourElement.innerHTML = `
<div class="hourly-time">${timeString}</div>
<img class="hourly-icon" src="https://openweathermap.org/img/wn/${iconCode}.png" alt="Weather icon">
<div class="hourly-temp">${temp}°</div>
`;
hourlyForecast.appendChild(hourElement);
}
}
// Display daily forecast
function displayDailyForecast(data) {
dailyForecast.innerHTML = '';
const dailyData = data.data_day;
if (!dailyData || !dailyData.temperature_max || dailyData.temperature_max.length === 0) {
dailyForecast.innerHTML = '<p>No daily data available</p>';
return;
}
// Skip today (index 0) if we want, but meteoblue data might be structured differently
// Let's show 7 days of forecast
const daysToShow = Math.min(7, dailyData.temperature_max.length);
for (let i = 0; i < daysToShow; i++) {
const dayElement = document.createElement('div');
dayElement.className = 'daily-item';
// Calculate date for this forecast
const forecastDate = new Date();
forecastDate.setDate(forecastDate.getDate() + i);
const dayName = forecastDate.toLocaleDateString([], { weekday: 'short' });
// Get temperatures
const maxTemp = Math.round(dailyData.temperature_max[i]);
const minTemp = Math.round(dailyData.temperature_min[i]);
// Determine weather condition and icon
let iconCode = "01d";
if (dailyData.precipitation && dailyData.precipitation[i] > 5) {
iconCode = "10d";
} else if (dailyData.cloudcover && dailyData.cloudcover[i] > 80) {
iconCode = "04d";
} else if (dailyData.cloudcover && dailyData.cloudcover[i] > 50) {
iconCode = "03d";
} else if (dailyData.cloudcover && dailyData.cloudcover[i] > 20) {
iconCode = "02d";
}
// Adjust for day/night (use day icons for daily forecast)
dayElement.innerHTML = `
<div class="daily-day">${dayName}</div>
<img class="daily-icon" src="https://openweathermap.org/img/wn/${iconCode}@2x.png" alt="Weather icon">
<div class="daily-temp">
<span class="daily-temp-high">${maxTemp}°</span>
<span class="daily-temp-low">${minTemp}°</span>
</div>
`;
dailyForecast.appendChild(dayElement);
}
}
// Toggle between light and dark mode
function toggleTheme() {
const body = document.body;
const isDarkMode = body.classList.contains('dark-mode');
if (isDarkMode) {
body.classList.remove('dark-mode');
localStorage.setItem('weatherly-theme', 'light');
themeToggle.innerHTML = '<i class="fas fa-moon"></i>';
} else {
body.classList.add('dark-mode');
localStorage.setItem('weatherly-theme', 'dark');
themeToggle.innerHTML = '<i class="fas fa-sun"></i>';
}
}
// Load theme from localStorage
function loadTheme() {
const savedTheme = localStorage.getItem('weatherly-theme');
if (savedTheme === 'dark') {
document.body.classList.add('dark-mode');
themeToggle.innerHTML = '<i class="fas fa-sun"></i>';
}
}
// Load favorites from localStorage
function loadFavorites() {
favoritesList.innerHTML = '';
if (favorites.length === 0) {
favoritesList.innerHTML = '<p>No favorite locations yet. Search for a location to add it!</p>';
return;
}
favorites.forEach(fav => {
const favElement = document.createElement('div');
favElement.className = 'favorite-item';
favElement.innerHTML = `
${fav.name}
<span class="remove-favorite" data-name="${fav.name}"><i class="fas fa-times"></i></span>
`;
favElement.addEventListener('click', (e) => {
if (e.target.closest('.remove-favorite')) {
const name = e.target.closest('.remove-favorite').getAttribute('data-name');
removeFromFavorites(name);
} else {
currentLocation = { lat: fav.lat, lon: fav.lon, asl: fav.asl || 100, name: fav.name };
fetchWeatherData();
}
});
favoritesList.appendChild(favElement);
});
}
// Add current location to favorites if not already there
function addToFavoritesIfNeeded(name, lat, lon) {
const exists = favorites.some(fav => fav.name === name);
if (!exists) {
const newFavorite = {
name,
lat,
lon,
asl: currentLocation.asl || 100
};
favorites.push(newFavorite);
localStorage.setItem('weatherly-favorites', JSON.stringify(favorites));
loadFavorites();
}
}
// Remove location from favorites
function removeFromFavorites(name) {
favorites = favorites.filter(fav => fav.name !== name);
localStorage.setItem('weatherly-favorites', JSON.stringify(favorites));
loadFavorites();
}
// Show loading state
function showLoading() {
locationName.textContent = 'Loading...';
weatherCondition.textContent = 'Fetching weather data';
currentTemp.textContent = '--°';
feelsLike.textContent = 'Feels like --°';
// Clear previous forecast data
hourlyForecast.innerHTML = '<div class="loading"></div>';
dailyForecast.innerHTML = '<div class="loading"></div>';
}
// Show error message
function showError(message) {
locationName.textContent = 'Error';
weatherCondition.textContent = message;
currentTemp.textContent = '--°';
feelsLike.textContent = '';
hourlyForecast.innerHTML = `<div class="error">${message}</div>`;
dailyForecast.innerHTML = `<div class="error">${message}</div>`;
}