-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgetWeather.js
More file actions
307 lines (283 loc) · 9.8 KB
/
getWeather.js
File metadata and controls
307 lines (283 loc) · 9.8 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
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
const API_KEY = "25159f62ee4b6390eaf7d424869031ac";
// returns a promise
function getTempByZipCode(zipCode) {
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
xhr.onload = () => {
if (xhr.status === 200) {
const weather = JSON.parse(xhr.responseText);
qTemp = KelvToFahr(weather.main.temp);
resolve([zipCode, qTemp]);
} else {
reject(xhr.statusText);
}
};
const url = "api.openweathermap.org/data/2.5/weather?zip=";
const endpoint = "https://" + url + zipCode + "&appid=" + API_KEY;
xhr.open('GET', endpoint, true);
xhr.send();
});
}
// returns a promise!
function getTempByCity(city, countryCode) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.onload = () => {
if (xhr.status === 200) {
const weather = JSON.parse(xhr.responseText);
const qTemp = KelvToFahr(weather.main.temp);
// console.log(city, countryCode, qTemp);
resolve([city, countryCode, qTemp]);
} else {
reject(xhr.status);
}
};
const endpoint = `https://api.openweathermap.org/data/2.5/weather?q=${city},${countryCode}&appid=${API_KEY}`;
xhr.open('GET', endpoint, true);
try {
xhr.send();
} catch (err) {
console.log(`There was an error with ${city}, ${countryCode}`);
}
});
}
// Let's AJAX this in. Or format it so that there's no newline
function getCitiesArray(numOfCities) {
return Promise.resolve([
['Tokyo', 'JP'],
['Delhi', 'IN'],
['Mumbai', 'IN'],
['Manila', 'PH'],
['Shanghai', 'CN'],
['Seoul', 'KR'],
['Mexico City', 'MX'],
['Guangzhou', 'CN'],
['Beijing', 'CN'],
['Cairo', 'EG'],
['Moscow', 'RU'],
['Bangkok', 'TH'],
['Buenos Aires', 'AR'],
['Shenzhen', 'CN'],
['Dhaka', 'BD'],
['Lagos', 'NG'],
['Istanbul', 'TR'],
['Osaka', 'JP'],
['Karachi', 'PK'],
['Bangalore', 'IN'],
['Tehran', 'IR'],
['Kinshasa', 'CD'],
['Ho Chi Minh City', 'VN'],
['Rio de Janeiro', 'BR'],
['Nanyang', 'CN'],
['Chennai', 'IN'],
['Chengdu', 'CN'],
['Lahore', 'PK'],
['Paris', 'FR'],
['London', 'GB'],
['Lima', 'PE'],
['Hyderabad', 'IN'],
['Bogota', 'CO'],
['Weifang', 'CN'],
['Nagoya', 'JP'],
['Wuhan', 'CN'],
['Luanda', 'AO'],
['Kuala Lumpur', 'MY'],
['Hanoi', 'VN'],
['Pune', 'IN'],
['Onitsha', 'NG'],
['Nanjing', 'CN'],
['Hong Kong', 'HK'],
['Khartoum', 'SD'],
['Santiago', 'CL'],
['Riyadh', 'SA'],
['Dar es Salaam', 'TZ'],
['Surat', 'IN'],
['Baghdad', 'IQ'],
['Singapore', 'SG'],
['Nairobi', 'KE'],
['Ankara', 'TR'],
['Rangoon', 'MM'],
['Toronto', 'CA'],
['Saint Petersburg', 'RU'],
['Sydney', 'AU'],
['Guadalajara', 'MX'],
['Belo Horizonte', 'BR'],
['Melbourne', 'AU'],
['Surabaya', 'ID'],
['Abidjan', 'CI'],
['Alexandria', 'EG'],
['Barcelona', 'ES'],
['Johannesburg', 'ZA'],
['Casablanca', 'MA'],
['Izmir', 'TR'],
['Monterrey', 'MX'],
['Amman', 'JO'],
['Jeddah', 'SA'],
['Yokohama', 'JP'],
['Kabul', 'AF'],
['Berlin', 'DE'],
['Montreal', 'CA'],
['Busan', ' KR'],
['Algiers', 'DZ'],
['Lucknow', 'IN'],
['Madrid', 'ES'],
['Faisalabad', 'PK'],
['Santa Cruz', 'BO'],
['Jaipur', 'IN'],
['Addis Ababa', 'ET'],
['Giza', 'EG'],
['Brasilia', 'BR'],
['Mashhad', 'IR'],
['Kyiv', 'UA'],
['Sanaa', 'YE'],
['Quezon City', 'PH'],
['Salvador', 'BR'],
['Incheon', 'KR'],
['Bursa', 'TR'],
['Birmingham', 'GB'],
['Rome', 'IT'],
['La Paz', 'BO'],
['Pyongyang', 'KP'],
['Kano', 'NG']
].slice(0, numOfCities));
}
function getTemp(json) {
try {
return KelvToFahr(json.main.temp);
} catch (error) {
return null;
}
}
function KelvToFahr(k) {
return ((k - 273.15) * 9 / 5) + 32;
}
function findClosestTemp(targetT, cityTemps) {
let bestTempDiff = Number.MAX_SAFE_INTEGER;
let currentBestCity = [];
for (let city of cityTemps) {
const tempDiff = Math.abs(targetT - city.value[2]);
// console.log("target: ", targetT, "currentBest: ", currentBestCity, "compare: ", city.value);
if (tempDiff < bestTempDiff) {
currentBestCity = city.value;
bestTempDiff = tempDiff;
}
}
return currentBestCity;
}
function getNewHtml(qCity, qTemp, newCity, newTemp) {
let xhr = new XMLHttpRequest();
xhr.onload = () => {
if (xhr.status === 200) {
document.getElementById('content').setAttribute('class', 'fadeOut');
setTimeout(() => {
let request = xhr.responseText;
document.getElementById('content').innerHTML = request;
let spans = document.getElementsByTagName('span');
spans[0].textContent = newCity;
spans[1].textContent = newTemp + '°F';
spans[2].textContent = newCity;
spans[3].textContent = qTemp + '°F';
spans[4].textContent = qCity;
//add the image in, this function is in showImage.js
getPictureOfCity(newCity);
// Handle button action and push effect
const backButton = document.getElementById('backButton');
backButton.addEventListener('click', goBack, false);
window.addEventListener('keydown', (e) => {
if (e.key !== "Enter") return;
backButton.setAttribute('class', 'hover');
});
window.addEventListener('keyup', (e) => {
if (e.key !== "Enter") return;
backButton.classList.remove('hover');
backButton.click();
}, false);
window.removeEventListener('click', handler);
window.addEventListener('click', () => {
document.querySelector('.anim5').classList.add('skip-anim');
document.querySelector('.anim6').classList.add('skip-anim');
let anim7 = document.querySelectorAll('.anim7');
anim7[0].classList.add('skip-anim');
anim7[1].classList.add('skip-anim');
document.querySelector('.anim8').classList.add('skip-anim');
});
document.querySelector("a").setAttribute('href', generateWikipediaLink(newCity));
}, 1000);
}
};
xhr.open('GET', 'searchResult.html', false);
xhr.send(null);
}
function goBack(e) {
location.reload();
}
function loadErrorMessage() {
document.getElementById('error').textContent = "Error: Please enter a valid ZIP Code.";
}
function generateWikipediaLink(cityName) {
const q = cityName.replace(/ /g, "_");
return `https://en.wikipedia.org/wiki/${q}`;
}
// MAIN
getWeatherPromise = function (query) {
console.log('Searching...');
getCitiesArray(100).then((cities) => {
console.log("Number of cities being searched: ", cities.length);
let tempProms = [];
tempProms.push(getTempByZipCode(query));
for (const city of cities) {
tempProms.push(getTempByCity(city[0], city[1]));
}
let promAll = Promise.allSettled(tempProms).catch(e => {
console.log("Error: ", e);
});
return promAll;
}).then(cityTemps => {
return new Promise((resolve, reject) => {
let qTemp = cityTemps[0].value[1]; //the array indices aren't very revealling... this is the temp.
let searchTemps = cityTemps.slice(1, cityTemps.length);
let closestTemp = findClosestTemp(qTemp, searchTemps);
// console.log("closestTemp:", closestTemp, "(queryTemp: ", qTemp, ")");
getNewHtml(query, qTemp.toFixed(), closestTemp[0], closestTemp[2].toFixed());
resolve(closestTemp);
});
}).catch(e => {
console.log("Error: ", e);
loadErrorMessage();
});
};
//helper function for the event listener to skip
function handler() {
document.querySelector('.anim1').classList.add('skip-anim');
document.querySelector('.anim2').classList.add('skip-anim');
document.querySelector('.anim3').classList.add('skip-anim');
document.querySelector('.anim4').classList.add('skip-anim');
setTimeout(() => {
try {
document.getElementById('form').click();
} catch (err) {}
}, 250);
}
window.addEventListener('load', () => {
window.addEventListener('click', handler);
// Add event listener to form, to help users find the box
document.getElementById("form").addEventListener('click', () => {
document.getElementById('zipCode').focus();
});
let btn = document.getElementById('submit');
btn.addEventListener('click', () => {
let zip = document.getElementById('zipCode');
getWeatherPromise(zip.value);
});
window.addEventListener('keydown', (e) => {
if (e.key !== "Enter") return;
btn.setAttribute('class', 'hover');
});
window.addEventListener('keyup', (e) => {
if (e.key !== "Enter") return;
btn.classList.remove('hover');
e.preventDefault();
// console.log('default Prevented');
btn.click();
});
});