Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
48 lines (39 loc) · 1.39 KB
/
Copy pathscript.js
File metadata and controls
48 lines (39 loc) · 1.39 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
function getWeather() {
const city = document.getElementById("city").value;
const resultBox = document.getElementById("result-box");
document.getElementById("result").innerHTML = "Loading...";
resultBox.style.display = "block";
// STEP 1: City → Coordinates
const geoURL = `https://geocoding-api.open-meteo.com/v1/search?name=${city}`;
fetch(geoURL)
.then(response => response.json())
.then(geoData => {
if (!geoData.results) {
document.getElementById("result").innerHTML = "City not found!";
return; // stop here
}
const lat = geoData.results[0].latitude;
const lon = geoData.results[0].longitude;
// STEP 2: Weather API
const weatherURL =
`https://api.open-meteo.com/v1/forecast?latitude=${lat}&longitude=${lon}¤t_weather=true`;
return fetch(weatherURL);
})
.then(response => {
if (!response) return; // if city not found
return response.json();
})
.then(weatherData => {
if (!weatherData) return;
const w = weatherData.current_weather;
document.getElementById("result").innerHTML = `
<b>Temperature:</b> ${w.temperature}°C<br>
<b>Wind Speed:</b> ${w.windspeed} km/h<br>
<b>Time:</b> ${w.time}
`;
})
.catch(error => {
console.error(error);
document.getElementById("result").innerHTML = "Error fetching data!";
});
}