-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
459 lines (360 loc) · 16.3 KB
/
script.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
import { wmoDescriptions } from './weatherDescriptions.js'
// ================= API =================
const unsplashAccessKey = 'NnSrMv3s7SE9KwQjg_9bQ4f1LXaYD-fWiZw9McMEZRY';
const opencageApiKey = '19f4cb4132ce48a2a78bc47868811d46';
const apiUrl = 'https://archive-api.open-meteo.com/v1/archive';
const nasaAPI = fetch("https://mars.nasa.gov/rss/api/?feed=weather&category=msl&feedtype=json");
// ================= CONSTANTS & VARIABLES =================
const defaultCity = 'London'; // Default city is set to London
let isSearchButtonClicked = false;
let marsDates = [];
let marsDatesReady = false;
let userCity = defaultCity;
let formSubmittedWhileLoading = null;
// Store the current background image URL
let currentBackgroundImage = '';
const DEFAULT_IMAGE = 'mars';
// ================= DOM ELEMENTS =================
const buttons = document.querySelectorAll('.filter-btn');
const backgroundContainer = document.querySelector('.background-container');
// ================= MAIN FUNCTIONS =================
//Updates the city for the user and initiates an image fetch.
function updateUserCity(city) {
userCity = city;
clearErrorMessage();
fetchUnsplashImage();
}
async function getGeolocation(city) {
const geocodingUrl = `https://api.opencagedata.com/geocode/v1/json?q=${encodeURIComponent(city)}&key=${opencageApiKey}`;
try {
const response = await fetch(geocodingUrl);
if (!response.ok) {
throw new Error(`Failed to fetch geolocation data: ${response.status} ${response.statusText}`);
}
const data = await response.json();
const firstResult = data.results[0];
if (firstResult) {
const { lat, lng } = firstResult.geometry;
return { latitude: lat, longitude: lng };
} else {
throw new Error(`No results found for the city: ${city}`);
}
} catch (error) {
console.error('Error fetching geolocation data:', error);
throw error;
}
}
// ================= UTILITY FUNCTIONS =================
// Clear the error message
function clearErrorMessage() {
const errorElement = document.querySelector('.error-message');
if (errorElement) {
errorElement.style.display = 'none';
}
}
// Displays a given error message on the screen
function displayErrorMessage(message) {
const errorElement = document.querySelector('.error-message');
if (errorElement) {
errorElement.textContent = message;
errorElement.style.display = 'block';
}
}
//Set the background image
function setBackgroundImage(imageUrl) {
const backgroundContainer = document.querySelector('.background-image');
// console.log('Background container:', backgroundContainer); // Debugging line
if (!backgroundContainer) {
console.error('Background container not found!');
return;
}
// Append a timestamp to the URL to prevent caching
imageUrl += `?timestamp=${new Date().getTime()}`;
backgroundContainer.style.backgroundImage = `url(${imageUrl})`;
backgroundContainer.style.backgroundSize = 'cover';
backgroundContainer.style.backgroundRepeat = 'no-repeat';
}
async function translateWMOCodeToDescription(weatherCodes) {
try {
const descriptions = [];
for (const code of weatherCodes) {
const codeString = code.toString().padStart(2, '0'); // Ensure the code is two digits
if (wmoDescriptions[codeString]) {
const description = wmoDescriptions[codeString];
descriptions.push(description);
} else {
console.warn(`No description found for weather code: ${codeString}`);
descriptions.push('Unknown weather');
}
}
return descriptions;
} catch (error) {
console.error('Error translating weather code to description:', error);
return ['Error fetching weather description'];
}
}
// ================= Parameter API data storage =================
const parameterData = {
mars: {
terrestrial_date: [],
atmoOpacities: [],
minAirTemp: [],
maxAirTemp: [],
sunrise: [],
sunset: [],
solData: []
},
earth: {
atmoOpacities: [],
minAirTemp: [],
maxAirTemp: [],
sunrise: [],
sunset: []
}
}
// ================= FETCHING FUNCTIONS =================
// Fetches an image from Unsplash based on the user's city input.
async function fetchUnsplashImage() {
const cityName = userCity;
// Check if the "Search" button is clicked before fetching the image
if (!isSearchButtonClicked) {
return;
}
const unsplashUrl = `https://api.unsplash.com/search/photos?query=${cityName}&orientation=landscape`;
console.log('Requesting Unsplash URL:', unsplashUrl);
try {
const response = await fetch(unsplashUrl, {
headers: {
Authorization: `Client-ID ${unsplashAccessKey}`,
},
});
// If the fetch isn't successful, retrieve a Mars image
if (!response.ok) {
// throw new Error(`Failed to fetch image from NASA ${response.status} ${response.statusText}`);
await fetchMarsImage();
return;
}
const data = await response.json();
// If no images are found for the user's city, retrieve a Mars image
if (!data.results || data.results.length === 0) {
displayErrorMessage(`No images found for ${cityName} on Unsplash.`);
await fetchMarsImage();
return;
}
const imageUrl = data.results[0].urls.full; // Get the URL of the first image
// Store the fetched image URL as the current background image
currentBackgroundImage = imageUrl;
// Set the fetched image as the background of the container
setBackgroundImage(imageUrl);
} catch (error) {
console.error('Error fetching image from Unsplash:', error);
await fetchMarsImage(); // When there's an error, fetch Mars image from Unsplash
}
}
//Fetch an image of Mars
async function fetchMarsImage() {
const unsplashUrl = `https://api.unsplash.com/search/photos?query=mars&orientation=landscape`;
try {
const response = await fetch(unsplashUrl, {
headers: {
Authorization: `Client-ID ${unsplashAccessKey}`,
},
});
if (!response.ok) {
console.error(`Failed to fetch Mars image from Unsplash: ${response.status} ${response.statusText}`);
throw new Error('Failed to fetch Mars image from Unsplash.');
}
const data = await response.json();
const imageUrl = data.results[0].urls.full; // Get the URL of the first Mars image
// Set the fetched Mars image as the background
setBackgroundImage(imageUrl);
} catch (marsError) {
console.error('Error fetching Mars image from Unsplash:', marsError);
// Displaying an error message to the user
displayErrorMessage('We encountered an error while fetching a background image. Please try again later.');
}
}
async function handleWeatherFormSubmission(event, marsDates) {
event.preventDefault();
// Start the loading indicator
document.getElementById('loadingIndicator').style.display = 'flex';
await new Promise(resolve => setTimeout(resolve, 1000));
const cityInput = document.getElementById('earthCityInput');
const cityInputValue = cityInput.value;
if (cityInputValue) {
userCity = cityInputValue; // update userCity
try {
const { latitude, longitude } = await getGeolocation(cityInputValue);
const promises = marsDates.map((marsDate, dayIndex) =>
fetchWeather(latitude, longitude, marsDate, dayIndex)
);
await Promise.all(promises); // Wait for all fetches to complete
// Stop the loading indicator after all fetches are done
document.getElementById('loadingIndicator').style.display = 'none';
} catch (error) {
console.error('Error processing form submission:', error);
// Handle the error, display a message to the user, etc.
}
} else {
// Stop the loading indicator after all fetches are done
document.getElementById('loadingIndicator').style.display = 'none';
alert("Please enter a valid city name.");
await fetchMarsImage();
}
}
async function fetchWeather(latitude, longitude, marsDate, dayIndex) {
const params = {
latitude,
longitude,
start_date: marsDate,
end_date: marsDate,
daily: 'weather_code,temperature_2m_max,temperature_2m_min,sunrise,sunset',
temperature_unit: 'celsius',
wind_speed_unit: 'kmh',
precipitation_unit: 'mm',
timezone: 'GMT',
};
const url = new URL(apiUrl);
url.search = new URLSearchParams(params);
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Failed to fetch data: ${response.status} ${response.statusText}`);
}
const data = await response.json();
console.log('Weather data for date', marsDate, 'in', latitude, longitude, data);
// Update the arrays for Earth with data for the selected day (dayIndex)
const dailyData = data.daily; // Access the daily object
const weatherDescriptions = await translateWMOCodeToDescription(dailyData.weather_code);
if (dailyData) {
parameterData.earth.atmoOpacities[dayIndex] = weatherDescriptions;
parameterData.earth.maxAirTemp[dayIndex] = dailyData.temperature_2m_max[0];
parameterData.earth.minAirTemp[dayIndex] = dailyData.temperature_2m_min[0];
parameterData.earth.sunrise[dayIndex] = dailyData.sunrise[0];
parameterData.earth.sunset[dayIndex] = dailyData.sunset[0];
} else {
throw new Error(`Invalid response format for date ${marsDate}`);
}
document.getElementById('loadingIndicator').style.display = 'none';
} catch (error) {
console.error('Fetch error:', error);
document.getElementById('loadingIndicator').style.display = 'none';
// Clear the arrays for this city and Mars date combination
parameterData.earth.atmoOpacities[dayIndex] = null;
parameterData.earth.minAirTemp[dayIndex] = null;
parameterData.earth.maxAirTemp[dayIndex] = null;
parameterData.earth.sunrise[dayIndex] = null;
parameterData.earth.sunset[dayIndex] = null;
}
}
// ================= NASA MARS API =================
document.getElementById('loadingIndicator').style.display = 'block';
nasaAPI
.then((response) => response.json())
.then((marsData) => {
const solsArray = marsData.soles;
solsArray.sort((a, b) => new Date(b.First_UTC) - new Date(a.First_UTC));
const last7Sols = solsArray.slice(0, 7);
console.log(last7Sols);
// Extract the terrestrial_date from the Mars API data
marsDates = last7Sols.map(sol => {
const dateParts = sol.terrestrial_date.split('-'); // Split the date string
const year = dateParts[0];
const month = dateParts[1];
const day = dateParts[2];
// Define an array of month names
const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
return `${year}-${month.padStart(2, '0')}-${day.padStart(2, '0')}`;
;
});
console.log(marsDates);
// Populate the buttons with terrestrial dates
buttons.forEach((button, index) => {
button.textContent = marsDates[index];
console.log("Mars Parameter Data:", parameterData.mars);
});
// Fill parameterData object with obtained data for both Mars and Earth
parameterData.mars.terrestrial_date = last7Sols.map(sol => sol.terrestrial_date);
parameterData.mars.atmoOpacities = last7Sols.map(sol => sol.atmo_opacity);
parameterData.mars.minAirTemp = last7Sols.map(sol => sol.min_temp);
parameterData.mars.maxAirTemp = last7Sols.map(sol => sol.max_temp);
parameterData.mars.sunrise = last7Sols.map(sol => sol.sunrise);
parameterData.mars.sunset = last7Sols.map(sol => sol.sunset);
parameterData.mars.solData = last7Sols;
// Set the flag to indicate that marsDates is ready
marsDatesReady = true;
// Check if the form was submitted while loading
if (formSubmittedWhileLoading) {
handleWeatherFormSubmission(formSubmittedWhileLoading.event, marsDates);
}
// Stop the loading indicator after processing the data
document.getElementById('loadingIndicator').style.display = 'none';
})
.catch((error) => console.log(error));
// Stop the loading indicator in case of error
document.getElementById('loadingIndicator').style.display = 'none';
// ================= EVENT LISTENERS & INITIALISATION =================
// Event listener for the form submission
document.addEventListener('DOMContentLoaded', function () {
const cityInput = document.getElementById('earthCityInput');
cityInput.value = defaultCity;
const weatherForm = document.getElementById('weather-search-form');
weatherForm.addEventListener('submit', async (event) => {
event.preventDefault(); // Prevent the form from submitting by default
// Check if the user has entered a city name
const userCity = cityInput.value.trim();
if (userCity === '') {
alert('Please enter a city name before searching.');
await fetchMarsImage();
return; // Do not proceed with the search if no city is entered
}
if (marsDatesReady) {
isSearchButtonClicked = true; // Set the flag when the "Search" button is clicked
await handleWeatherFormSubmission(event, marsDates);
// Update the background image based on the user's input city
fetchUnsplashImage();
} else {
// If marsDates is not ready, store the form submission data
formSubmittedWhileLoading = { event, marsDates };
}
});
});
//Attach click event listeners to the buttons
buttons.forEach((button, index) => {
button.addEventListener('click', () => {
// Call the updateTableData function with the clicked button's index
updateTableData(index);
});
});
// ================= TABLE =================
// Function to update table cells based on the selected index
async function updateTableData(index) { // Make sure this is an async function
console.log('Updating table for index:', index);
const solData = parameterData.mars.solData[index];
const earthSunrise = parameterData.earth.sunrise[index];
const earthSunset = parameterData.earth.sunset[index];
// Convert Earth sunrise and sunset to the desired format
const convertedEarthSunrise = formatTime(earthSunrise);
const convertedEarthSunset = formatTime(earthSunset);
// Update the Earth data cells
const solNumber = solData.sol;
document.getElementById('soleDate').textContent = `SOL ${solNumber}`;
document.getElementById('earthMinAirTemp').textContent = parameterData.earth.minAirTemp[index];
document.getElementById('earthMaxAirTemp').textContent = parameterData.earth.maxAirTemp[index]
document.getElementById('earthAtmoOpacities').textContent = parameterData.earth.atmoOpacities[index];
document.getElementById('earthSunrise').textContent = convertedEarthSunrise;
document.getElementById('earthSunset').textContent = convertedEarthSunset;
// Update the Mars data cells
document.getElementById('marsMinAirTemp').textContent = parameterData.mars.minAirTemp[index];
document.getElementById('marsMaxAirTemp').textContent = parameterData.mars.maxAirTemp[index];
document.getElementById('marsAtmoOpacities').textContent = parameterData.mars.atmoOpacities[index];
document.getElementById('marsSunrise').textContent = parameterData.mars.sunrise[index];
document.getElementById('marsSunset').textContent = parameterData.mars.sunset[index];
}
// Helper function to format time (AM/PM to 24-hour format)
function formatTime(timeString) {
const date = new Date(timeString);
const hours = date.getHours();
const minutes = date.getMinutes();
return `${hours}:${minutes}`;
}