-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
247 lines (244 loc) · 7.27 KB
/
script.js
File metadata and controls
247 lines (244 loc) · 7.27 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
const apikey = "INSERT YOUR OWN KEY HERE";
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
var cover = document.getElementById("coverpage");
var details = document.getElementById("details");
var days = {};
document.addEventListener('DOMContentLoaded', function() {
closeDetails();
coverpage.addEventListener("click", function(e){
if(e.target == this)
closeDetails();
});
var loc = navigator.geolocation.getCurrentPosition(getCoords, error, options);
}, false);
document.getElementById("location").addEventListener("keydown", function(e){
if(e.keyCode == 13){
getWeather({city: this.value}, function(arr){
//console.log(arr);
document.getElementById("forecast").innerHTML = "";
setInputText(`${arr.city.name}, ${arr.city.country}`);
days = {};
for (let i = 0; i < arr.list.length; i++) {
let item = arr.list[i];
let dateInText = getDateinText(item.dt_txt);
if(!days.hasOwnProperty(dateInText)){
days[dateInText] = {
timestamp: [],
weather: [],
weather_icon: [],
temp: [],
temp_min: [],
temp_max: [],
pressure: []
};
}
days[dateInText].timestamp.push(item.dt);
days[dateInText].weather.push(item.weather[0].main);
days[dateInText].weather_icon.push(item.weather[0].icon);
days[dateInText].temp.push(item.main.temp);
days[dateInText].temp_min.push(item.main.temp_min);
days[dateInText].temp_max.push(item.main.temp_max);
days[dateInText].pressure.push(item.main.pressure);
}
for(day in days){
let obj = averageAll(days[day]);
obj.date = day;
addItemToForecast(obj);
}
});
}
});
function getCoords(position){
var roundedCoords = {
lat: position.coords.latitude,
lon: position.coords.longitude
}
getWeather({coords: roundedCoords}, function(arr){
//console.log(arr);
setInputText(`${arr.city.name}, ${arr.city.country}`);
days = {};
for (let i = 0; i < arr.list.length; i++) {
let item = arr.list[i];
let dateInText = getDateinText(item.dt_txt);
if(!days.hasOwnProperty(dateInText)){
days[dateInText] = {
timestamp: [],
weather: [],
weather_icon: [],
temp: [],
temp_min: [],
temp_max: [],
pressure: []
};
}
days[dateInText].timestamp.push(item.dt);
days[dateInText].weather.push(item.weather[0].main);
days[dateInText].weather_icon.push(item.weather[0].icon);
days[dateInText].temp.push(item.main.temp);
days[dateInText].temp_min.push(item.main.temp_min);
days[dateInText].temp_max.push(item.main.temp_max);
days[dateInText].pressure.push(item.main.pressure);
}
for(day in days){
let obj = averageAll(days[day]);
obj.date = day;
//console.log(days);
//console.log(obj);
addItemToForecast(obj);
}
});
}
function error(err) {
console.warn(`ERROR(${err.code}): ${err.message}`);
setInputText("");
}
function getDateinText(str){
return str.substr(0,10);
}
function averageAll(obj){
var r = {};
for(key in obj){
if(key !== "weather" && key !== "weather_icon"){
if(key !== "temp"){
r[key] = average(obj[key]);
}
else{
r[key] = Math.max(...obj[key]);
}
}
else{
if(key === "weather"){
r[key] = mode(obj[key]);
r["weather_icon"] = obj["weather_icon"][obj[key].indexOf(r[key])];
}
}
}
return r;
}
function average(arr){
var sum, avg = 0;
if (arr.length)
{
sum = arr.reduce(function(a, b) { return a + b; });
avg = sum / arr.length;
}
return avg;
}
function getWeather(location, callback)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(JSON.parse(xmlHttp.responseText));
else if(xmlHttp.readyState == 4 && xmlHttp.status == 404){
setInputText(`Error: ${JSON.parse(xmlHttp.responseText).message}`);
}
}
var params = "";
if(location.hasOwnProperty("city")) params = `q=${location.city}`;
else if (location.hasOwnProperty("coords")) params = `lat=${location.coords.lat}&lon=${location.coords.lon}`;
//console.log(params);
xmlHttp.open("GET", `https://api.openweathermap.org/data/2.5/forecast?${params}&appid=${apikey}`, true);
xmlHttp.send(null);
}
function setInputText(text){
document.getElementById("location").value = text;
}
var forecastWrapper = document.getElementById("forecast");
function addItemToForecast(obj){
var short = {
weather: obj.weather, //.join("/")
temp: kelvinToCelsius(obj.temp),
}
var itemWrapper = createElementWithClass("div","forecast--item");
itemWrapper.addEventListener("click", function(){
showDetailedForecast(obj.date);
});
var itemHeading = createElementWithClass("h2", "", obj.date);
itemWrapper.appendChild(itemHeading);
for(key in short){
if(key === "weather" || key === "icon"){
let newItem = createElementWithClass("i", `wi ${getIcon(obj.weather_icon)}`);
itemWrapper.appendChild(newItem);
}
let newItem = createElementWithClass("h3",key,short[key]);
itemWrapper.appendChild(newItem);
}
forecastWrapper.appendChild(itemWrapper);
}
function createElementWithClass(tagName, className, content){
className = className || "";
var tag = document.createElement(tagName);
tag.className = className;
if(content){
var t = document.createTextNode(content);
tag.appendChild(t);
}
return tag;
}
function kelvinToCelsius(k) {
return `${Math.round(k-273.15)} °C`;
}
function showDetailedForecast(date){
coverpage.className = "visible";
var btn = document.createElement("a");
btn.href = "#";
btn.className = "closeBtn";
btn.innerText = "×";
btn.addEventListener("click", closeDetails);
details.appendChild(btn);
var flex = document.createElement("div");
flex.id = "details--flexbox";
var heading = createElementWithClass("h2", "", date);
details.appendChild(heading);
details.appendChild(flex);
for (var i = 0; i < days[date].timestamp.length; i++) {
var wrapper = document.createElement("div");
//console.log(days[date]);
var item = createElementWithClass("h3", "time", timestampToTime(days[date].timestamp[i]));
wrapper.appendChild(item);
item = createElementWithClass("i", `wi ${getIcon(days[date].weather_icon[i])}`);
wrapper.appendChild(item);
if(!days[date].weather[i]) days[date].weather[i] = days[date].weather[i-1];
item = createElementWithClass("h3", "weather", days[date].weather[i]);
wrapper.appendChild(item);
item = createElementWithClass("h3", "temp", kelvinToCelsius(days[date].temp[i]));
wrapper.appendChild(item);
flex.appendChild(wrapper);
}
}
function getIcon(weatherIcon){
weatherIcon = weatherIcon || "01d";
let key = `i${weatherIcon.substr(0, 2)}`;
let i = weatherIcon.substr(-1) === "n" ? 0 : 1;
var icons = {
i01: ["day-sunny", "night-clear"],
i02: ["day-cloudy", "night-alt-cloudy"],
i03: ["cloud", "cloud"],
i04: ["cloudy", "cloudy"],
i09: ["rain", "rain"],
i10: ["day-rain", "night-alt-rain"],
i11: ["wi-thunderstorm", "wi-thunderstorm"],
i13: ["wi-snow", "wi-snow"],
};
var r = `wi-${icons[key][i]}`;
return r;
}
function mode(arr){
return arr.sort((a,b) =>
arr.filter(v => v===a).length
- arr.filter(v => v===b).length
).pop();
}
function closeDetails(){
coverpage.className = "";
details.innerHTML = "";
}
function timestampToTime(ts){
var d = new Date(ts*1000);
return `${("0"+d.getHours()).substr(-2)}:${("0"+d.getMinutes()).substr(-2)}`;
}