-
Notifications
You must be signed in to change notification settings - Fork 0
/
weatherapi.js
317 lines (291 loc) · 11.7 KB
/
weatherapi.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
async function fetch_json(url) {
const response = await fetch(url)
return await response.json()
}
function geolocate() {
return new Promise((resolve, reject) => {
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(resolve, reject, {
enableHighAccuracy: true
});
} else {
console.debug("no geolocation available")
reject("no geolocation available")
}
})
}
function f_to_c(f) {
return (f - 32) * (5 / 9);
}
function c_to_f(c) {
return (c * (9 / 5)) + 32
}
function openweathermap_api_request(lat, long) {
return fetch_json(`https://api.openweathermap.org/data/3.0/onecall?lat=${encodeURIComponent(lat)}&lon=${encodeURIComponent(long)}&appid=74b014b3526434e435b0b553d9f673e1&units=metric`)
}
function nws_api_forecast(lat, long) {
return fetch_json(`https://api.weather.gov/points/${encodeURIComponent(lat)},${encodeURIComponent(long)}`).then(points => {
return fetch_json(points["properties"]["forecastGridData"])
})
}
function nws_api_request(lat, long) {
// nws is weird so this has to be done weirdly
return Promise.all([
nws_api_forecast(lat, long),
fetch_json(`https://api.weather.gov/alerts/active?status=actual&message_type=alert,update,cancel&point=${encodeURIComponent(lat)},${encodeURIComponent(long)}`)
]).then(resp => {
return {
"forecast": resp[0],
"alerts": resp[1]
}
})
}
function parse_iso8601_date(date) {
if (date === "NOW") {
return new Date();
} else {
return date.parse(date)
}
}
function parse_iso8601_duration(duration) {
let match = iso8601_duration_regex.exec(duration);
let years = match[1] || 0;
let months = match[2] || 0;
let days = match[3] || 0;
let hours = match[4] || 0;
let minutes = match[5] || 0;
let seconds = match[6] || 0;
return years * (1000 * 60 * 60 * 24 * 365) +
months * (1000 * 60 * 60 * 24 * 30) +
days * (1000 * 60 * 60 * 24) +
hours * (1000 * 60 * 60) +
minutes * (1000 * 60) +
seconds * 1000;
}
// lightly modified from nws docs
const iso8601_start_and_end_regex = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:Z|[+-]\d{2}:?\d{2}?)|NOW)\/(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:Z|[+-]\d{2}:?\d{2}?)|NOW)$/
const iso8601_start_and_duration_regex = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:Z|[+-]\d{2}:?\d{2}?)|NOW)\/(P(\d+Y)?(\d+M)?(\d+D)?(?:T(\d+H)?(\d+M)?(\d+S)?)?)$/;
const iso8601_duration_and_end_regex = /^(P(\d+Y)?(\d+M)?(\d+D)?(?:T(\d+H)?(\d+M)?(\d+S)?)?)\/(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:Z|[+-]\d{2}:?\d{2}?)|NOW)$/
const iso8601_duration_regex = /P(?<years>\d+Y)?(\d+M)?(\d+D)?(?:T(\d+H)?(\d+M)?(\d+S)?)?/;
function parse_iso8601_interval(interval) {
// nws only appears to use start + duration but docs say it can be any of these 3 so
if (iso8601_start_and_end_regex.test(interval)) {
let match = iso8601_start_and_end_regex.exec(interval);
let start = parse_iso8601_date(match[1]);
let end = parse_iso8601_date(match[2]);
return [start, end - start];
} else if (iso8601_start_and_duration_regex.test(interval)) {
let match = iso8601_start_and_duration_regex.exec(interval);
let start = parse_iso8601_date(match[1]);
let duration = parse_iso8601_duration(match[2]);
return [start, duration];
}
if (iso8601_duration_and_end_regex.test(interval)) {
let match = iso8601_duration_and_end_regex.exec(interval);
let duration = parse_iso8601_duration(match[1]);
let end = parse_iso8601_date(match[2]);
let start = new Date(end.getTime() - duration);
return [start, duration];
} else {
throw new Error("Unable to parse " + interval);
}
}
const generic_template = {
"currently": {
"summary": "Lorem ipsum",
"temperature": 0,
"apparent_temperature": 0,
"humidity": 0,
"cloud_cover": 0,
"precipitation": 0
},
"hourly": {
"summary": "Lorem ipsum",
"temperature": [{x: 0, y: 0}/*, ...*/],
"apparent_temperature": [{x: 0, y: 0}/*, ...*/],
"humidity": [{x: 0, y: 0}/*, ...*/],
"cloud_cover": [{x: 0, y: 0}/*, ...*/],
"precipitation": [{x: 0, y: 0}/*, ...*/],
},
"daily": {
"summary": "Lorem ipsum",
"high": [{x: 0, y: 0}/*, ...*/],
"apparent_high": [{x: 0, y: 0}/*, ...*/],
"low": [{x: 0, y: 0}/*, ...*/],
"apparent_low": [{x: 0, y: 0}/*, ...*/],
"feels_like": [{x: 0, y: 0}/*, ...*/],
"humidity": [{x: 0, y: 0}/*, ...*/],
"cloud_cover": [{x: 0, y: 0}/*, ...*/],
"precipitation": [{x: 0, y: 0}/*, ...*/],
},
"alerts": [
{
"severity": "advisory", // advisory, watch, warning
"url": "https://example.com",
"title": "Lorem ipsum",
"expires": 0,
}//, ...
],
"source": "openweathermap", // openweathermap, etc
}
function zip_openweathermap(data, property, multiply_y_by = 1) {
return data.map(data_point => {
let y = data_point[property] ?? 0;
y *= multiply_y_by
return {x: data_point["dt"] * 1000, y: y}
})
}
const openweathermap_icons = {
// clear sky
"01d": {"climacon": "sun", "fontawesome": "sun"},
"01n": {"climacon": "moon", "fontawesome": "moon"},
// few clouds
"02d": {"climacon": "sun cloud", "fontawesome": "cloud-sun"},
"02n": {"climacon": "moon cloud", "fontawesome": "cloud-moon"},
// scattered clouds
"03d": {"climacon": "cloud", "fontawesome": "cloud"},
"03n": {"climacon": "cloud", "fontawesome": "cloud"},
// broken clouds
"04d": {"climacon": "cloud", "fontawesome": "clouds"},
"04n": {"climacon": "cloud", "fontawesome": "clouds"},
// shower rain
"09d": {"climacon": "drizzle", "fontawesome": "cloud-showers"},
"09n": {"climacon": "drizzle", "fontawesome": "cloud-showers"},
// rain
"10d": {"climacon": "rain", "fontawesome": "cloud-showers-heavy"},
"10n": {"climacon": "rain", "fontawesome": "cloud-showers-heavy"},
// thunderstorm
"11d": {"climacon": "lightning", "fontawesome": "cloud-bolt"},
"11n": {"climacon": "lightning", "fontawesome": "cloud-bolt"},
// snow
"13d": {"climacon": "snowflake", "fontawesome": "snowflake"},
"13n": {"climacon": "snowflake", "fontawesome": "snowflake"},
// mist
"50d": {"climacon": "fog", "fontawesome": "cloud-fog"},
"50n": {"climacon": "fog", "fontawesome": "cloud-fog"},
}
function openweathermap_sum_precip_over_hour(hour) {
return (hour["rain"] ? hour["rain"]["1h"] : 0) +
(hour["snow"] ? hour["snow"]["1h"] : 0)
}
function parse_openweathermap(data) {
console.debug(data);
return {
"currently": {
"summary": data["current"]["weather"][0]["description"],
"temperature": data["current"]["temp"],
"apparent_temperature": data["current"]["feels_like"],
"humidity": data["current"]["humidity"],
"cloud_cover": data["current"]["clouds"],
"precipitation_intensity": openweathermap_sum_precip_over_hour(data["current"]),
"icon": openweathermap_icons[data["current"]["weather"][0]["icon"]]
},
"hourly": {
"summary": data["daily"][0]["summary"],
"temperature": zip_openweathermap(data["hourly"], "temp"),
"apparent_temperature": zip_openweathermap(data["hourly"], "feels_like"),
"humidity": zip_openweathermap(data["hourly"], "humidity"),
"cloud_cover": zip_openweathermap(data["hourly"], "clouds"),
"precipitation_probability": zip_openweathermap(data["hourly"], "pop", 100),
"precipitation_intensity": data["hourly"].map(hour => {
return {x: hour["dt"] * 1000, y: openweathermap_sum_precip_over_hour(hour)}
}),
},
"daily": {
"summary": "",
"high": data["daily"].map(data_point => {
return {x: data_point["dt"] * 1000, y: data_point["temp"]["max"]}
}),
"apparent_high": data["daily"].map(data_point => {
// ugh why
return {x: data_point["dt"] * 1000, y: Math.max(...Object.values(data_point["feels_like"]))}
}),
"low": data["daily"].map(data_point => {
return {x: data_point["dt"] * 1000, y: data_point["temp"]["min"]}
}),
"apparent_low": data["daily"].map(data_point => {
return {x: data_point["dt"] * 1000, y: Math.min(...Object.values(data_point["feels_like"]))}
}),
"humidity": zip_openweathermap(data["daily"], "humidity"),
"cloud_cover": zip_openweathermap(data["daily"], "clouds"),
"precipitation_probability": zip_openweathermap(data["daily"], "pop", 100),
"precipitation_intensity": zip_openweathermap(data["daily"], "rain"),
},
"alerts": (data["alerts"] ?? []).map(alert => {
return {
"severity": alert["severity"], // advisory, watch, warning
"url": "",
"title": alert["event"],
"description": alert["description"],
"expires": alert["end"],
}
}),
"source": "openweathermap", // darksky,openweathermap,openmeteo, etc
}
}
function parse_nws(data) {
return {
"currently": {
"summary": "Lorem ipsum",
"temperature": 0,
"apparent_temperature": 0,
"humidity": 0,
"cloud_cover": 0,
"precipitation": 0
},
"hourly": {
"summary": "Lorem ipsum",
"temperature": [{x: 0, y: 0}/*, ...*/],
"apparent_temperature": [{x: 0, y: 0}/*, ...*/],
"humidity": [{x: 0, y: 0}/*, ...*/],
"cloud_cover": [{x: 0, y: 0}/*, ...*/],
"precipitation": [{x: 0, y: 0}/*, ...*/],
},
"daily": {
"summary": "Lorem ipsum",
"high": [{x: 0, y: 0}/*, ...*/],
"apparent_high": [{x: 0, y: 0}/*, ...*/],
"low": [{x: 0, y: 0}/*, ...*/],
"apparent_low": [{x: 0, y: 0}/*, ...*/],
"feels_like": [{x: 0, y: 0}/*, ...*/],
"humidity": [{x: 0, y: 0}/*, ...*/],
"cloud_cover": [{x: 0, y: 0}/*, ...*/],
"precipitation": [{x: 0, y: 0}/*, ...*/],
},
"alerts": [
{
"severity": "advisory", // advisory, watch, warning
"url": "https://example.com",
"title": "Lorem ipsum",
"expires": 0,
}//, ...
],
"source": "nws", // darksky,openweathermap, etc
}
}
function get_weather_from_latlong(lat, long, provider) {
switch (provider) {
case "openweathermap":
return openweathermap_api_request(lat, long).then(parse_openweathermap)
case "nws":
return nws_api_request(lat, long).then(parse_nws)
}
}
function geocode(addr) {
return fetch_json(`https://api.openweathermap.org/geo/1.0/direct?q=${addr}&limit=1&appid=74b014b3526434e435b0b553d9f673e1`).then(r => {
if (r && r.length) {
return {
"latitude": r[0]["lat"],
"longitude": r[0]["lon"]
}
} else {
return null
}
})
}
function reverse_geocode(lat, long) {
return fetch_json(`https://api.openweathermap.org/geo/1.0/reverse?lat=${encodeURIComponent(lat)}&lon=${encodeURIComponent(long)}&appid=74b014b3526434e435b0b553d9f673e1&limit=1`).then(r => {
// name(, state), country
return `${r[0]["name"]}${r[0]["state"] ? `, ${r[0]["state"]}` : ""}, ${r[0]["country"]}`;
})
}