-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
202 lines (190 loc) · 6.8 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
//get resources from index.html;
const temperature = document.querySelector('.temperature');
const season = document.querySelector('.season');
const view = document.querySelectorAll('.view');
const weekday = document.querySelector('.date');
const errorDisplay = document.querySelector('.errorMessage');
const mainLocation = document.querySelector('.location');
const loader = document.querySelector('.loader');
window.addEventListener('load', () => {
let long;
let lat;
const setPosition = (position) => {
lat = 40.7143;
long = -74.006;
recieveGeoCoord(lat, long);
}
const showError = (error) => {
if(error){
handleError(error)
console.log('from showError error', error)
showSaved()
}
}
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(setPosition, showError);
} else {
errorDisplay.innerHTML = '<p> BROWSER NOT SUPPORTED!! </p>';
}
});
function showSaved () {
let savedWeather = JSON.parse(window.localStorage.getItem('weatherInfo'))
console.log('saved weathher', savedWeather);
if(savedWeather){
const lastSave = document.querySelector('.saveMessage');
lastSave.innerHTML = `<p class="last-save">Showing last searched result`;
setTimeout(() => {
lastSave.innerHTML = '';
}, 3000);
showWeatherDetails(savedWeather);
}
}
// Sending the fetch data with the user search word
const fetchData = async (lat, long) => { //async on the
const api = `https://api.openweathermap.org/data/2.5/onecall?lat=${lat}&lon=${long}&exclude=hourly,minutely&units=metric&appid=putinakey`;
const response = await fetch(api);
return response;
}
const p = document.querySelector('.error');
function handleError(error) {
loader.className += ' hidden';
p.innerText = (error.code === 2) ? 'Internet not connected' : error.message;
errorDisplay.appendChild(p);
return;
}
function renderOption(data) {
const {icon, main} = data.weather[0];
const date = new Date(data.dt * 1000);
const days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
const day = days[ date.getDay() ];
const {min, max} = data.temp;
return `
<div class="special">
<div class="sub">
<img class="sub-icon view" src="./icons/${icon}.png" alt="${day} is ${main}">
<h2 class="sub-season">${main}</h2>
</div>
<p class="style weekday">${day}</p>
<h3 class="side-temp">${Math.round(max)} <span class='low-side-temp'> ${Math.round(min)}</span></h3>
<h4 class="degree">°C</h4>
</div>
`
}
function showClock(timestamp) {
const clock = document.querySelector('.clock');
let time = new Date(timestamp * 1000);
clock.innerText = time.toLocaleTimeString();
}
function showDate(timestamp, element) {
const days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
const months = [
'Jan', 'Feb',
'Mar', 'Apr',
'May', 'Jun',
'Jul', 'Aug',
'Sep', 'Oct',
'Nov', 'Dec'
];
//this should get the date.
const date = new Date(timestamp * 1000);
let day = days[ date.getDay() ];
let month = months[ date.getMonth() ];
let year = date.getFullYear();
let todate = date.getDate();
// whole day format.
let theDate = `${day}, ${todate} ${month} ${year}`;
element.innerText = theDate;
showClock(timestamp);
}
function showWeatherDetails(data) {
const list = document.querySelector('.list');
const eventSafe = document.querySelector('.safe');
const {timezone} = data;
const {temp, dt} = data.current;
const {description,icon, main} = data.current.weather[0];
loader.className += ' hidden';
eventSafe.innerText = (main === 'Clear' || main === 'Clouds') ? 'Safe' : 'Not Safe';
(!mainLocation.innerText) ? mainLocation.innerText = timezone : '';
temperature.innerText = Math.round(temp);
season.innerText = description;
view.forEach(image => {
image.setAttribute('src', `./icons/${icon}.png`);
image.setAttribute('alt', `it is currently ${description}`);
});
list.innerHTML = '';
showDate(dt, weekday)
const daily = data.daily.slice(0, 5);
for(let day of daily){
const div = document.createElement('div');
div.innerHTML = renderOption(day);
list.appendChild(div);
}
}
const recieveGeoCoord = (lat, long) => {
fetchData(lat, long).then(response => {
return response.json();
}).then(data => {
window.localStorage.setItem('weatherInfo', JSON.stringify(data))
showWeatherDetails(data);
}).catch(err => {
showSaved();
handleError(err);
} );
}
const inputFetch = async (search) => {
const url = `https://api.openweathermap.org/data/2.5/weather?q=${search}&appid=putinakey`;
const response = await fetch(url);
return response;
}
const inputShield = (func, delay = 1000) => {
let timeOutID;
return (...args) => {
if(timeOutID) {
clearTimeout(timeOutID)
}
timeOutID = setTimeout(() => {
func.apply(null, args)
}, delay);
}
}
const onInput = async (event) => {
if (event.target.value) {
loader.className = 'loader';
const movies = await inputFetch(event.target.value)
.then(response => {
return response.json();
}).then(data => {
console.log('FROM INPUT', data);
if (data.cod == "404") {
handleError(data);
}
if(data.coord){
const lat = data.coord.lat;
const lon = data.coord.lon;
errorDisplay.innerHTML = '';
mainLocation.innerText = data.name;
recieveGeoCoord(lat, lon);
}
}).catch(err => {
showSaved();
console.log('from input error', err)
handleError(err);
})
} else {
return;
}
};
const inputBox = document.querySelector('#search');
inputBox.addEventListener('input', inputShield(onInput, 1000) );
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('./sw.js')
.then(function(registration) {
// Regsuccessful
console.log('ServiceWorker registration successful:', registration.scope);
}, function(err) {
//failed
console.log('ServiceWorker registration failed: ', err);
});
});
}