-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
74 lines (59 loc) · 2.45 KB
/
Copy pathscript.js
File metadata and controls
74 lines (59 loc) · 2.45 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
const input = document.getElementById('location');
const form = document.getElementById('weather-form');
const result = document.getElementById('weather-result');
form.addEventListener('submit', async (e) => {
e.preventDefault();
const location = input.value.trim();
if (!location) {
showError("Please enter a valid location.");
return;
}
showLoading();
try {
const weatherData = await fetchWeatherData(location);
displayWeatherData(weatherData);
} catch (error) {
showError(error.message || "Failed to fetch weather data.");
}
});
async function fetchWeatherData(location) {
const geoURL = `https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(location)}`;
const geoResponse = await fetch(geoURL);
if (!geoResponse.ok) {
throw new Error("Network error while fetching location data.");
}
const geoData = await geoResponse.json();
if (!geoData.results || geoData.results.length === 0) {
throw new Error("Location not found. Please try a different city.");
}
const { latitude, longitude, name, country } = geoData.results[0];
const weatherURL = `https://api.open-meteo.com/v1/forecast?latitude=${latitude}&longitude=${longitude}¤t_weather=true`;
const weatherResponse = await fetch(weatherURL);
if (!weatherResponse.ok) {
throw new Error("Network error while fetching weather data.");
}
const weatherData = await weatherResponse.json();
return { ...weatherData, locationName: `${name}, ${country}` };
}
function displayWeatherData(data) {
const {
current_weather: { temperature, windspeed, winddirection },
current_weather_units: { temperature: tempUnit, windspeed: windUnit, winddirection: dirUnit },
locationName
} = data;
result.style.display = "block";
result.innerHTML = `
<h2 style="margin-bottom: 10px;">Current Weather in ${locationName}</h2>
<p><strong>Temperature:</strong> ${temperature} ${tempUnit}</p>
<p><strong>Wind Speed:</strong> ${windspeed} ${windUnit}</p>
<p><strong>Wind Direction:</strong> ${winddirection}${dirUnit} (relative to North)</p>
`;
}
function showLoading() {
result.style.display = "block";
result.innerHTML = "<p>Loading weather data...</p>";
}
function showError(message) {
result.style.display = "block";
result.innerHTML = `<p style="color: red; font-weight: bold;">${message}</p>`;
}