-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
349 lines (311 loc) · 11.7 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
"use strict";
const inputValue = document.getElementById("input-value");
const submitBtn = document.getElementById("submit");
const tempEl = document.getElementById("temp");
const tempFeelEl = document.getElementById("feel");
const tempMinEl = document.getElementById("min");
const tempMaxEl = document.getElementById("max");
const nameEl = document.getElementById("city");
const windtSpeedEl = document.getElementById("wind-speed");
const windDirEl = document.getElementById("wind-dir");
const pressureEl = document.getElementById("pressure");
const conditionsEl = document.getElementById("conditions");
const humEl = document.getElementById("humidity");
const countryEl = document.getElementById("country");
const sunriseEl = document.getElementById("sunrise");
const sunsetEl = document.getElementById("sunset");
const clockEl = document.getElementById("clock");
const localClockEl = document.getElementById("local-clock");
const localTimeEl = document.getElementById("local-time-container");
const airPollutionEl = document.getElementById("air-pollution");
const airPollutionContainer = document.getElementById("loader");
const airProgressEl = document.getElementById("air-progress");
const airPollutionIcn = document.getElementById("air-icon");
const testing = document.querySelector(".testing");
const forecastSectionEl = document.getElementById("forecast");
const loader = document.querySelector(".loader");
const backgroundImageStyle = document.body.style;
const bgLoader = document.querySelector("#bg-img-loader");
let cityName;
let lat;
let lon;
let apiKey = "fb574912b0999ba535af23dc7e4332dd";
let units = "metric";
// GET USER LOCATION AND PRINT WEATHER
function success(pos) {
let location = pos.coords;
lat = location.latitude;
lon = location.longitude;
// console.log(location);
fetch(
`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${apiKey}&units=metric`
)
.then((response) => {
if (!response.ok) throw new Error(`error: ${response.status}`);
return response.json();
})
.then((data) => {
getWeather(data.name);
});
}
navigator.geolocation.getCurrentPosition(success);
// GET WEATHER FUNCTION
function getWeather(city) {
// loader animation
loader.classList.add("show-loader");
// fetching data
fetch(
`https://api.openweathermap.org/geo/1.0/direct?q=${city}&limit=1&appid=${apiKey}`
)
.then((response) => {
if (!response.ok) throw new Error(`error ${response.status}`);
loader.classList.remove("show-loader");
return response.json();
})
.then((cityData) => {
lat = cityData[0].lat;
lon = cityData[0].lon;
cityName = cityData[0].name;
})
.catch((err) => {
console.log("City not found");
document.getElementById("input-error").innerHTML =
"Brak takiego miasta w bazie";
setTimeout(() => {
document.getElementById("input-error").innerHTML = "";
}, 3000);
return response.json();
})
.then(() => {
// GET WEATHER BASED ON GEOCODE
getData(lat, lon);
// GET AIR POLLUTION DATA
getAir();
// RESET FORECAST DIV!
forecastSectionEl.innerHTML = "";
// GET FORECAST FUNCTION
getDailyForecast();
});
}
// SUBMIT SEARCH INPUT VIA SEARCH BUTTON
submitBtn.addEventListener("click", () => {
document.getElementById("input-error").innerHTML = "";
if (inputValue.value == "") {
document.getElementById("input-error").innerHTML =
"This field could not be empty";
return;
}
cityName = inputValue.value;
getWeather(cityName);
});
// SUBMIT SEARCH INPUT VIA ENTER KEY
inputValue.addEventListener("keydown", (e) => {
if (e.key == "Enter") {
document.getElementById("input-error").innerHTML = "";
if (inputValue.value == "") {
document.getElementById("input-error").innerHTML =
"This field could not be empty";
return;
}
cityName = inputValue.value;
getWeather(cityName);
} else return;
});
document
.getElementById("forecast-details-btn--left")
.addEventListener("click", () => {
document.getElementById("details").classList.toggle("hide-details");
forecastSectionEl.classList.toggle("hide-forecast");
});
document
.getElementById("forecast-details-btn--right")
.addEventListener("click", () => {
document.getElementById("details").classList.toggle("hide-details");
forecastSectionEl.classList.toggle("hide-forecast");
});
// GET CEOLOCATION BY INPUTET
// GET WEATHER BASED ON GEOLOCATION
function getData(lat, lon) {
fetch(
`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${apiKey}&units=metric`
)
.then((response) => {
if (!response.ok) throw new Error(`error: ${response.status}`);
return response.json();
})
.then((data) => {
// DESTRUCTURING OUTPUT
// const city = data.name;
const { temp, pressure, humidity, feels_like, temp_max, temp_min } =
data.main;
const { speed, deg } = data.wind;
const { country, sunrise, sunset } = data.sys;
const icon = data.weather[0].icon;
const timezone = data.timezone;
// PRINTING RESULTS TO THE DOM
tempEl.innerHTML = Math.round(temp) + "°";
tempFeelEl.innerHTML = Math.round(feels_like) + "°";
tempMinEl.innerHTML = Math.round(temp_max) + "°";
tempMaxEl.innerHTML = Math.round(temp_min) + "°";
nameEl.innerHTML = cityName;
windtSpeedEl.innerHTML = Math.round(speed) + "m/s";
windDirEl.style.transform = `rotate(${deg - 45}deg)`;
pressureEl.innerHTML = pressure + " hPa";
humEl.innerHTML = humidity + "%";
conditionsEl.src = `img/${icon}.png`;
// Check if bg image is avaliable and set background
const backgroundSource = `https://source.unsplash.com/1200x720/?${cityName}`;
// backgroundImageStyle.background = "black";
backgroundImageStyle.backgroundImage = `url(https://source.unsplash.com/1200x720/?${cityName})`;
const setBackground = function () {
backgroundImageStyle.backgroundImage = "grey";
bgLoader.classList.add("bg-active");
fetch(backgroundSource).then((response) => {
if (response.url.includes("404")) {
bgLoader.classList.remove("bg-active");
backgroundImageStyle.backgroundImage = `url(
"https://images.unsplash.com/photo-1504608524841-42fe6f032b4b?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=765&q=80"
)`;
} else {
bgLoader.classList.remove("bg-active");
backgroundImageStyle.backgroundImage = `url(https://source.unsplash.com/1200x720/?${cityName})`;
}
});
};
setBackground();
countryEl.innerHTML = country;
// DATES AND TIMEZONES
const myDate = new Date();
const newDate = new Date(myDate);
newDate.setHours(newDate.getHours());
const sunriseTZ = sunrise + timezone - 3600;
const sunsetTZ = sunset + timezone - 3600;
timeConverter(sunriseTZ, sunsetTZ);
function ticker() {
const myDate = new Date();
const newDate = new Date(myDate);
newDate.setHours(
myDate.getHours() - myDate.toTimeString().slice(12, 15)
);
newDate.setHours(newDate.getHours() + timezone / 60 / 60);
if (myDate.getHours() !== newDate.getHours()) {
clockEl.textContent = myDate.toTimeString().slice(0, 8);
localTimeEl.classList.remove("hide");
localClockEl.textContent =
"Local " + newDate.toTimeString().slice(0, 5);
} else {
localTimeEl.classList.add("hide");
clockEl.textContent = myDate.toTimeString().slice(0, 8);
}
}
var myTimer = window.setInterval(ticker, 1000);
// SET NEW TIMER
inputValue.addEventListener("keydown", (e) => {
if (e.key == "Enter") {
window.clearInterval(myTimer);
} else return;
});
submitBtn.addEventListener("click", () => {
window.clearInterval(myTimer);
});
});
}
// AIR POLLUTION FUNCTION
function getAir() {
fetch(
`https://api.openweathermap.org/data/2.5/air_pollution?lat=${lat}&lon=${lon}&appid=${apiKey}`
)
.then((response) => response.json())
.then((airData) => {
const airPollution = airData.list[0].main.aqi;
if (airPollution === 1) {
airProgressEl.style.width = "10%";
airProgressEl.style.backgroundColor = "green";
airPollutionIcn.name = "happy";
}
if (airPollution === 2) {
airProgressEl.style.width = "40%";
airProgressEl.style.backgroundColor = "yellow";
airPollutionIcn.name = "happy";
}
if (airPollution === 3) {
airProgressEl.style.width = "60%";
airProgressEl.style.backgroundColor = "orange";
airPollutionIcn.name = "sad";
}
if (airPollution === 4) {
airProgressEl.style.width = "80%";
airProgressEl.style.backgroundColor = "violet";
airPollutionIcn.name = "sad";
}
if (airPollution === 5) {
airProgressEl.style.width = "100%";
airProgressEl.style.backgroundColor = "purple";
airPollutionIcn.name = "skull";
}
})
.catch((err) => {
console.log("air pollution", err);
});
}
// FORECAST FUNCTION
function getDailyForecast() {
fetch(
`https://api.openweathermap.org/data/2.5/onecall?lat=${lat}&lon=${lon}&exclude=hourly&appid=${apiKey}&units=metric`
)
.then((response) => response.json())
.then((forecastData) => {
let i = 1;
for (let i = 1; i < 4; i++) {
const { day, night } = forecastData.daily[i].temp;
const { icon } = forecastData.daily[i].weather[0];
const forecastDay = new Date(forecastData.daily[i].dt * 1000);
const forecastDayString = forecastDay.toString().slice(4, 11);
const dayOfWeek = forecastDay.toString().slice(0, 3);
const htmlTemplate = `
<div id="forecast-single" class="forecast-day">
<h4 class="forecast-title">${forecastDayString}</h4>
<h5 class="forecast-subtlite">${dayOfWeek}</h5>
<img src="./img/${icon}.png" id="conditions" class="img forecast"></img>
<div class="forecast-temp">
<ion-icon id="sunny-icn" class="forecast-icon-small" name="sunny"></ion-icon>
<div id='forecast-day' class="sunrise">${Math.floor(day)}°</div>
<ion-icon id="sunset-icn" class="forecast-icon-small" name="moon"></ion-icon>
<div id='forecast-night' class="sunset">${Math.floor(
night
)}°</div>
</div>
</div>
`;
forecastSectionEl.innerHTML += htmlTemplate;
}
})
.then(() => {
// loader remover
loader.classList.remove("show-loader");
});
}
// TIME FORMAT
const msToHMS = function (duration) {
var miliseconds = parseInt((duration % 1000) / 100),
seconds = parseInt((duration / 1000) % 60),
minutes = parseInt((duration / (1000 * 60)) % 60),
hours = parseInt((duration * 60 * 60) % 24);
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
return hours + ":" + minutes + ":" + seconds;
};
// SUNRISE CONVERTER
const timeConverter = function (sunrise, sunset) {
let date = new Date((sunrise - 3600) * 1000);
let hours = date.getHours();
let minutes = "0" + date.getMinutes();
let formattedSunrise = `${hours}:${minutes.substr(-2)}`;
let dateTwo = new Date((sunset - 3600) * 1000);
let hoursTwo = dateTwo.getHours();
let minutesTwo = "0" + dateTwo.getMinutes();
let formattedSunset = `${hoursTwo}:${minutesTwo.substr(-2)}`;
sunriseEl.innerHTML = formattedSunrise;
sunsetEl.innerHTML = formattedSunset;
};