-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
233 lines (226 loc) · 9.05 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
let cityInput = document.getElementById('city_input'),
searchBtn = document.getElementById('searchBtn'),
locationBtn = document.getElementById('locationBtn'),
api_key = 'b4827588e27f4a146bd4c12704303595';
currentWeatherCard = document.querySelectorAll('.weather-left .card')[0],
fiveDaysForecastCard = document.querySelector('.day-forecast'),
aqiCard = document.querySelectorAll('.highlights .card')[0],
sunriseCard = document.querySelectorAll('.highlights .card')[1],
humidityVal = document.getElementById('humidityVal'),
pressureVal = document.getElementById('pressureVal'),
visibilityVal = document.getElementById('visibilityVal'),
windSpeedVal = document.getElementById('windSpeedVal'),
feelsVal = document.getElementById('feelsVal'),
hourlyForecastCard = document.querySelector('.hourly-forecast'),
aqiList = ['Good', 'Fair', 'Moderate', 'Poor', 'Very Poor'];
function getWeatherDetails(name, lat, lon, country, state) {
let FORECAST_API_URL = `https://api.openweathermap.org/data/2.5/forecast?lat=${lat}&lon=${lon}&appid=${api_key}`,
WEATHER_API_URL = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${api_key}`,
AIR_POLLUTION_API_URL = `httpS://api.openweathermap.org/data/2.5/air_pollution?lat=${lat}&lon=${lon}&appid=${api_key}`,
days = [
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday'
],
months = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec'
];
fetch(AIR_POLLUTION_API_URL).then(res => res.json()).then(data => {
let{co, no, no2, o3, so2, pm2_5, pm10, nh3} = data.list[0].components;
aqiCard.innerHTML = `
<div class="card-head">
<p>Air Quality Index</p>
<p class="air-index aqi-${data.list[0].main.aqi}">${aqiList[data.list[0].main.aqi - 1]}</p>
</div>
<div class="air-indices">
<i class="fa-solid fa-wind fa-3x"></i>
<div class="item">
<p>PM2.5</p>
<h2>${pm2_5}</h2>
</div>
<div class="item">
<p>PM10</p>
<h2>${pm10}</h2>
</div>
<div class="item">
<p>SO<sup> 2</sup></p>
<h2>${so2}</h2>
</div>
<div class="item">
<p>CO</p>
<h2>${co}</h2>
</div>
<div class="item">
<p>NO</p>
<h2>${no}</h2>
</div>
<div class="item">
<p>NO<sup> 2</sup></p>
<h2>${no2}</h2>
</div>
<div class="item">
<p>NH<sub> 3</sub></p>
<h2>${nh3}</h2>
</div>
<div class="item">
<p>O<sup> 3</sup></p>
<h2>${o3}</h2>
</div>
</div>
`;
}).catch(() => {
alert("Failed to fetch air pollution!");
});
fetch(WEATHER_API_URL).then(res => res.json()).then(data => {
let date = new Date();
currentWeatherCard.innerHTML = `
<div class="card">
<div class="current-weather">
<div class="details">
<p>Now</p>
<h2>${(data.main.temp - 273.15).toFixed(2)}°C</h2>
<p>${data.weather[0].description}</p>
</div>
<div class="weather-icon">
<img src="https://openweathermap.org/img/wn/${data.weather[0].icon}@2x.png" alt="logo">
</div>
</div>
<hr>
<div class="card-footer">
<p><i class="fa-regular fa-calendar"></i> ${days[date.getDay()]}, ${date.getDate()}, ${months[date.getMonth()]}, ${date.getFullYear()}</p>
<p><i class="fa-solid fa-location-dot"></i> ${name}, ${country}</p>
</div>
</div>
`;
let {sunrise, sunset} = data.sys,
{timezone, visibility} = data,
{humidity, pressure, feels_like} = data.main,
{speed}= data.wind,
sRiseTime = moment.utc(sunrise, 'X').add(timezone,'seconds').format('hh:mm A'),
sSetTime = moment.utc(sunset, 'X').add(timezone,'seconds').format('hh:mm A');
sunriseCard.innerHTML = `
<div class="card-head">
<p>Sunrise & Sunset</p>
</div>
<div class="sunrise-sunset">
<div class="item">
<div class="icon">
<i class="fa-regular fa-sun fa-3x"></i>
<i class="fa-solid fa-arrow-up fa-3x"></i>
</div>
<div>
<p>Sunrise</p>
<h2>${sRiseTime}</h2>
</div>
</div>
<div class="item">
<div class="icon">
<i class="fa-regular fa-sun fa-3x"></i>
<i class="fa-solid fa-arrow-down fa-3x"></i>
</div>
<div>
<p>Sunset</p>
<h2>${sSetTime}</h2>
</div>
</div>
</div>
`;
humidityVal.innerHTML = `${humidity}%`;
pressureVal.innerHTML = `${pressure}hPa`;
visibilityVal.innerHTML = `${visibility/1000}km`;
windSpeedVal.innerHTML = `${speed}m/s`;
feelsVal.innerHTML = `${(feels_like - 273.15).toFixed(2)}°C`;
}).catch(() => {
alert("Failed to fetch current weather");
});
fetch(FORECAST_API_URL).then(res => res.json()).then(data => {
let hourlyForecast = data.list;
hourlyForecastCard.innerHTML = '';
for(i=0 ; i<=7 ; i++)
{
let hrForecastDate = new Date(hourlyForecast[i].dt_txt);
let hr = hrForecastDate.getHours();
let a = 'PM';
if(hr<12) a = 'AM';
if(hr == 0) hr = 12;
if(hr>12) hr = hr-12;
hourlyForecastCard.innerHTML +=`
<div class="card">
<p>${hr} ${a}</p>
<img src="https://openweathermap.org/img/wn/${hourlyForecast[i].weather[0].icon}.png" alt="">
<p>${(hourlyForecast[i].main.temp - 273.15).toFixed(2)}°C</p>
</div>
`;
}
let uniqueForecastDays = [];
let fiveDaysForecast = data.list.filter(forecast => {
let forecastDate = new Date(forecast.dt_txt).getDate();
if (!uniqueForecastDays.includes(forecastDate)) {
return uniqueForecastDays.push(forecastDate);
}
});
fiveDaysForecastCard.innerHTML = '';
for (i = 0; i < fiveDaysForecast.length; i++) {
let date = new Date(fiveDaysForecast[i].dt_txt);
fiveDaysForecastCard.innerHTML += `
<div class="forecast-item">
<div class="icon-wrapper">
<img src="https://openweathermap.org/img/wn/${fiveDaysForecast[i].weather[0].icon}.png" alt="icon">
<span>${(fiveDaysForecast[i].main.temp - 273.15).toFixed(2)}°C</span>
</div>
<p>${date.getDate()} ${months[date.getMonth()]}</p>
<p>${days[date.getDay()]}</p>
</div>
`;
}
}).catch(() => {
alert("Failed to fetch weather forecast!")
});
}
function getCityCoordinates() {
let cityName = cityInput.value.trim();
cityInput.value = '';
if (!cityName) return;
let GEOCODING_API_URL = `https://api.openweathermap.org/geo/1.0/direct?q=${cityName}&limit=1&appid=${api_key}`;
fetch(GEOCODING_API_URL).then(res => res.json()).then(data => {
let { name, lat, lon, country, state } = data[0];
getWeatherDetails(name, lat, lon, country, state);
}).catch(() => {
alert(`Failed to fetch coordinates of ${cityName}`);
});
}
function getUserCoordinates(){
navigator.geolocation.getCurrentPosition(position => {
let {latitude, longitude} = position.coords;
let REVERSE_GEOCODING_URL = `https://api.openweathermap.org/geo/1.0/reverse?lat=${latitude}&lon=${longitude}&limit=1&appid=${api_key}`;
fetch(REVERSE_GEOCODING_URL).then(res => res.json()).then(data => {
let {name, country, state} = data[0];
getWeatherDetails(name, latitude, longitude, country, state);
}).catch(() => {
alert("Failed to fetch User Coordinates!");
});
}, error => {
if(error.code === error.PERMISSION_DENIED){
alert("Geolocation permission denied. Please reset location permission to grant access again!");
}
});
}
searchBtn.addEventListener('click', getCityCoordinates);
locationBtn.addEventListener('click', getUserCoordinates);
cityInput.addEventListener('keyup', e => e.key === 'Enter' && getCityCoordinates());
window.addEventListener('load', getUserCoordinates());