-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
506 lines (428 loc) · 14.3 KB
/
index.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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
// openweather api
const myApiKey = '3070eaa7419d6c64f2a80da9e8f61d48';
const domClasses = {
date: document.querySelector('.currentdate'),
weather: document.querySelector('.weatherstat'),
weatherConditions: document.querySelector('.weather_conditions'),
dailyConditions: document.querySelector('.days_forecast'),
icon: document.querySelector('.currenticon'),
mychart: document.querySelector('.weather_forecast'),
searchLocation:document.querySelector('.searchbtn'),
searchedInput:document.querySelector('.searchinput'),
currentLocationWeather:document.querySelector('.currentlocation'),
loaderAnimation:document.querySelector('.loader'),
};
const displayDate = () => {
const months = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December',
];
const Days = [
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
];
const currentDate = new Date();
const currentDay = currentDate.getDate();
const currentMonth = currentDate.getMonth();
const currentYear = currentDate.getFullYear();
const Day = currentDate.getDay();
const currentHour = currentDate.getHours();
const todaysDay = Days[Day];
const Month = months[currentMonth];
let daysCount = [];
const countDown = (n) => {
if (n <= 0) {
return;
} else {
if (Day + n >= 7) {
daysCount.unshift(Days[Day + n - 7]);
} else {
daysCount.unshift(Days[Day + n]);
}
countDown(n - 1);
return daysCount;
}
};
countDown(5);
let hourCount = [];
const countDwn = (n) => {
if (n <= 0) {
return;
} else {
if (currentHour + n >= 24) {
currentHour + n - 24 < 10
? hourCount.unshift(`0${currentHour + n - 24}:00`)
: hourCount.unshift(`${currentHour + n - 24}:00`);
} else {
currentHour + n < 10
? hourCount.unshift(`0${currentHour + n}:00`)
: hourCount.unshift(`${currentHour + n}:00`);
}
countDwn(n - 1);
return hourCount;
}
};
countDwn(10);
const currentTimeStamp = {
currentDay: currentDay,
todaysDay: todaysDay,
Month: Month,
currentYear: currentYear,
daysCount: daysCount,
hourCount: hourCount,
};
return currentTimeStamp;
};
const uiDate = (currentDay, todaysDay, Month, currentYear) => {
let year = currentYear.toString();
const dateHtml = `
<span> ${todaysDay.slice(0, 3)}, ${currentDay} ${Month.slice(
0,
3
)} '${year.slice(2, 4)}</span>
`;
return dateHtml;
};
const weatherUi = (city, temp, condition, date) => {
const weatherDetails = `
<div>
<h4 class="temp">${Math.floor(temp)}°</h4>
</div>
<div class="locdate">
<div class="location">
<h2>${city}</h2>
<p>${date}</p>
</div>
</div>
<div>
<p class="cloud">${condition}</p>
</div>
`;
domClasses.weather.insertAdjacentHTML('afterbegin', weatherDetails);
};
const weatherConds = (wind, humidity, pressure, uv, min) => {
const condition = `
<h4 class="conditions_head">Weather conditions</h4>
<div class="conditondiv">
<div class="condition wind"><div><img alt="Wind" src="img/wind.svg" class="icons">Wind </div><div class="conditionvalue">${wind}m/s</div></div>
<div class="condition Precipitation"><div><img alt="pressure" src="img/barometer.svg" class="icons">Pressure</div> <div class="conditionvalue">${pressure}atm</div></div>
<div class="condition Humidity"><div><img alt="Humidity" src="img/humidity.svg" class="icons">Humidity</div> <div class="conditionvalue">${humidity}%</div></div>
<div class="condition wind"><div><img alt="ultra violet ray" src="img/uv-protection.svg" class="icons">UV</div> <div class="conditionvalue">${uv}</div></div>
</div>
`;
domClasses.weatherConditions.insertAdjacentHTML('afterbegin', condition);
};
const tenTemp = (el) => {
const arr = el.map((cur) => cur.temp);
return arr;
};
const lineChart = (hours, hourForecast) => {
const chart = document.querySelector('#myChart');
// chart.remove();
domClasses.mychart.innerHTML = ' ';
domClasses.mychart.insertAdjacentHTML(
'afterbegin',
'<canvas id="myChart" height="220" aria-label="weather forecast chart" role="img"></canvas>'
);
let lineChart = document.querySelector('#myChart');
var chartjs = new Chart(lineChart, {
type: 'line',
data: {
labels: hours,
datasets: [
{
label: 'Hourly Weather',
data: hourForecast,
backgroundColor: 'rgba(17, 119, 229, 0.6)',
borderColor: 'rgba(17, 119, 229, 0.3)',
pointBackgroundColor: 'transparent',
pointBorderColor: 'rgba(17, 119, 229, 0.7)',
pointHoverBorderColor: 'rgba(17, 119, 229, 0.9)',
pointHoverBorderWidth: 3,
borderWidth: 2,
fill: true,
},
],
},
options: {
responsive: true,
maintainAspectRatio: false,
tooltips: {
callbacks: {
label: function (tooltipItems, data) {
return tooltipItems.yLabel + '°C';
},
},
},
scales: {
yAxes: [
{
gridLines: {
drawOnChartArea: false,
},
},
],
xAxes: [
{
gridLines: {
drawOnChartArea: false,
},
},
],
},
legend: {
// display:false
},
},
});
};
const iconUi = (icon) => {
const iconUrl = `https://openweathermap.org/img/wn/${icon}@4x.png`;
domClasses.icon.insertAdjacentHTML('afterbegin',`<img class="currentweathericon" src="${iconUrl}" alt="Current Weather"></img>`)
};
const dailyUI = (day, Temperature, weather) => {
for (let i = 0; i < 6; i++) {
const UI = `
<div class="day">
<div class="">${day[i]}</div>
<div class="dayCondition">
<img alt="weather icon" src="https://openweathermap.org/img/wn/${
weather[i]['0'].icon
}@2x.png" class="dayIcon">
<br>
<span class="cond">${weather[i]['0'].description}</span>
</div>
<div class="daytemp">${Math.floor(
Temperature[i].temp.min
)}°c/${Math.floor(Temperature[i].temp.max)}°c</div>
</div>
`;
domClasses.dailyConditions.insertAdjacentHTML('beforeend', UI);
}
};
const HourlyWeather = (lat, long) => {
async function currentLocation() {
try {
//loader
// domClasses.loaderAnimation.classList.add('loadanimation')
const data = await fetch(
`https://api.openweathermap.org/data/2.5/onecall?lat=${lat}&lon=${long}&units=metric&appid=${myApiKey}`
); //daily and hourly forecast
// console.log(data)
const weather = await data.json();
// console.log(weather)
weatherConds(
weather.current.wind_speed,
weather.current.humidity,
weather.current.pressure,
weather.current.uvi,
weather.current.dew_point
);
// console.log(weather.hourly)
const tempHour = tenTemp(weather.hourly);
const HourlyW = tempHour.slice(0, 10);
const dailyW = weather.daily.slice(1, 6);
const date = displayDate();
lineChart(date.hourCount, HourlyW);
const dayWeather = dailyW.map((el) => {
return el.weather;
});
//Prepare UI
//remove loader
domClasses.loaderAnimation.classList.remove('loadanimation')
// console.log(dayWeather);
dailyUI(date.daysCount, dailyW, dayWeather);
} catch (error) {
// console.log(error);
}
}
currentLocation();
};
/**************************************** window load current weather **********************************************/
const weatherController = () => {
const weatherData = {};
//get current location weather
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition); //showPosition function with parameter position
} else {
alert('Geolocation is not supported by this browser.');
}
}
getLocation();
function showPosition(position) {
var locationlat = position.coords.latitude;
var locationlong = position.coords.longitude;
// console.log(locationlat, locationlong)
currentLocation(locationlat, locationlong);
HourlyWeather(locationlat, locationlong);
}
async function currentLocation(lat, long) {
try {
// loader
// domClasses.loaderAnimation.classList.add('loadanimation')
const data = await fetch(
`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&appid=${myApiKey}&units=metric`
); //current weather
const currentWeather = await data.json();
// console.log(currentWeather)
weatherData.cityName = currentWeather.name;
weatherData.weather = currentWeather.weather;
weatherData.temperature = currentWeather.main;
weatherData.wind = currentWeather.wind;
// console.log(weatherData)
//prepare UI
//remove loader
domClasses.loaderAnimation.classList.remove('loadanimation')
//display current weather
const date = displayDate();
weatherUi(
weatherData.cityName,
weatherData.temperature.temp,
weatherData.weather[0].description,
uiDate(date.currentDay, date.todaysDay, date.Month, date.currentYear)
);
iconUi(weatherData.weather[0].icon);
} catch (error) {
// console.log(error);
}
}
};
/**************************************search city weather**********************************************************/
const searchedHourlyWeather = (lat,long) => {
async function searchedLocation() {
try {
//loader
// domClasses.loaderAnimation.classList.add('loadanimation')
const data = await fetch(
`https://api.openweathermap.org/data/2.5/onecall?lat=${lat}&lon=${long}&units=metric&appid=${myApiKey}`
); //daily and hourly forecast
// console.log(data)
const weather = await data.json();
// console.log(weather)
weatherConds(
weather.current.wind_speed,
weather.current.humidity,
weather.current.pressure,
weather.current.uvi,
weather.current.dew_point
);
// console.log(weather.hourly)
const tempHour = tenTemp(weather.hourly);
const HourlyW = tempHour.slice(0, 10);
const dailyW = weather.daily.slice(1, 6);
const date = displayDate();
lineChart(date.hourCount, HourlyW);
const dayWeather = dailyW.map((el) => {
return el.weather;
});
//Prepare UI
//remove loader
domClasses.loaderAnimation.classList.remove('loadanimation')
// console.log(dayWeather);
dailyUI(date.daysCount, dailyW, dayWeather);
} catch (error) {
// console.log(error);
}
}
searchedLocation()
};
/**************************************** window load current weather **********************************************/
const searchedWeatherController = (searchInput) => {
const weatherData = {};
async function currentLocation() {
try {
// loader
// domClasses.loaderAnimation.classList.add('loadanimation')
const data = await fetch(
`https://api.openweathermap.org/data/2.5/weather?q=${searchInput}&appid=${myApiKey}&units=metric`
); //current weather
const currentWeather = await data.json();
// console.log(currentWeather)
weatherData.cityName = currentWeather.name;
weatherData.weather = currentWeather.weather;
weatherData.temperature = currentWeather.main;
weatherData.wind = currentWeather.wind;
weatherData.coord = currentWeather.coord
// console.log(weatherData)
searchedHourlyWeather(weatherData.coord.lat,weatherData.coord.lon)
//prepare UI
//remove loader
domClasses.loaderAnimation.classList.remove('loadanimation')
//display current weather
const date = displayDate();
weatherUi(
weatherData.cityName,
weatherData.temperature.temp,
weatherData.weather[0].description,
uiDate(date.currentDay, date.todaysDay, date.Month, date.currentYear)
);
iconUi(weatherData.weather[0].icon);
} catch (error) {
// console.log(error);
}
}
currentLocation()
};
const clearLayout = () =>{
domClasses.icon.innerHTML = ' ';
domClasses.mychart.innerHTML= ' ';
domClasses.weather.innerHTML = ' ';
domClasses.weatherConditions.innerHTML = ' ';
domClasses.dailyConditions.innerHTML = ' ';
domClasses.mychart.innerHTML= ' ';
}
const callLocation = () =>{
clearLayout()
domClasses.loaderAnimation.classList.add('loadanimation')
weatherController()
domClasses.currentLocationWeather.style.display = 'none';
}
const searchResult =()=>{
const Input = domClasses.searchedInput.value
if(Input === '' || Input === ' '){
alert('Enter a valid city name')
}else{
clearLayout();
domClasses.loaderAnimation.classList.add('loadanimation')
domClasses.searchedInput.value = '';
searchedWeatherController(Input)
domClasses.currentLocationWeather.style.display = 'inline-block';
}
}
domClasses.searchLocation.addEventListener('click',(e)=>{
e.preventDefault();
searchResult()
domClasses.searchLocation.blur()
})
document.addEventListener('keydown',(e)=>{
if(e.key === 'Enter'){
e.preventDefault()
searchResult()
domClasses.searchedInput.blur()
}
})
window.addEventListener('load', callLocation);
/**************************************** present location weather **********************************************/
domClasses.currentLocationWeather.addEventListener('click',callLocation);
//service worker
if('serviceWorker' in navigator){
navigator.serviceWorker.register('sw.js')
.then(()=>console.log('service worker registered'))
.catch(()=>'error registering sesrvice worker')
}