-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWeather.js
More file actions
35 lines (32 loc) · 1.24 KB
/
Weather.js
File metadata and controls
35 lines (32 loc) · 1.24 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
class Weather {
constructor(apiKey) {
this.apiKey = apiKey;
this.defaultLocation = 'New Delhi';
this.weatherData = null;
}
async fetchWeather(location = this.defaultLocation) {
const response = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${location}&appid=${this.apiKey}&units=metric`);
if (!response.ok) {
throw new Error('Failed to fetch weather data');
}
this.weatherData = await response.json();
return this.weatherData;
}
displayWeather(location) {
this.fetchWeather(location)
.then(data => {
const weatherContainer = document.getElementById('weather');
weatherContainer.innerHTML = `
<h2>Weather in ${data.name}</h2>
<p>Temperature: ${data.main.temp} °C</p>
<p>Condition: ${data.weather[0].description}</p>
`;
})
.catch(error => {
console.error(error);
const weatherContainer = document.getElementById('weather');
weatherContainer.innerHTML = `<p>Error fetching weather data. Please try again.</p>`;
});
}
}
export default Weather;