-
Notifications
You must be signed in to change notification settings - Fork 11
/
index.html
459 lines (408 loc) · 21.7 KB
/
index.html
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
<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.2.1/css/ol.css" type="text/css">
<style>
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
.map {
height: 100%;
width: 100%;
}
</style>
<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.2.1/build/ol.js"></script>
<title>OpenLayers example</title>
</head>
<body>
<div id="map" class="map">
</div>
<script type="text/javascript">
//download.js v4.2, by dandavis; 2008-2016. [CCBY2] see http://danml.com/download.html for tests/usage
// v1 landed a FF+Chrome compat way of downloading strings to local un-named files, upgraded to use a hidden frame and optional mime
// v2 added named files via a[download], msSaveBlob, IE (10+) support, and window.URL support for larger+faster saves than dataURLs
// v3 added dataURL and Blob Input, bind-toggle arity, and legacy dataURL fallback was improved with force-download mime and base64 support. 3.1 improved safari handling.
// v4 adds AMD/UMD, commonJS, and plain browser support
// v4.1 adds url download capability via solo URL argument (same domain/CORS only)
// v4.2 adds semantic variable names, long (over 2MB) dataURL support, and hidden by default temp anchors
// https://github.com/rndme/download
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define([], factory);
} else if (typeof exports === 'object') {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory();
} else {
// Browser globals (root is window)
root.download = factory();
}
}(this, function() {
return function download(data, strFileName, strMimeType) {
var self = window, // this script is only for browsers anyway...
defaultMime = "application/octet-stream", // this default mime also triggers iframe downloads
mimeType = strMimeType || defaultMime,
payload = data,
url = !strFileName && !strMimeType && payload,
anchor = document.createElement("a"),
toString = function(a) {
return String(a);
},
myBlob = (self.Blob || self.MozBlob || self.WebKitBlob || toString),
fileName = strFileName || "download",
blob,
reader;
myBlob = myBlob.call ? myBlob.bind(self) : Blob;
if (String(this) === "true") { //reverse arguments, allowing download.bind(true, "text/xml", "export.xml") to act as a callback
payload = [payload, mimeType];
mimeType = payload[0];
payload = payload[1];
}
if (url && url.length < 2048) { // if no filename and no mime, assume a url was passed as the only argument
fileName = url.split("/").pop().split("?")[0];
anchor.href = url; // assign href prop to temp anchor
if (anchor.href.indexOf(url) !== -1) { // if the browser determines that it's a potentially valid url path:
var ajax = new XMLHttpRequest();
ajax.open("GET", url, true);
ajax.responseType = 'blob';
ajax.onload = function(e) {
download(e.target.response, fileName, defaultMime);
};
setTimeout(function() {
ajax.send();
}, 0); // allows setting custom ajax headers using the return:
return ajax;
} // end if valid url?
} // end if url?
//go ahead and download dataURLs right away
if (/^data\:[\w+\-]+\/[\w+\-]+[,;]/.test(payload)) {
if (payload.length > (1024 * 1024 * 1.999) && myBlob !== toString) {
payload = dataUrlToBlob(payload);
mimeType = payload.type || defaultMime;
} else {
return navigator.msSaveBlob ? // IE10 can't do a[download], only Blobs:
navigator.msSaveBlob(dataUrlToBlob(payload), fileName) :
saver(payload); // everyone else can save dataURLs un-processed
}
} //end if dataURL passed?
blob = payload instanceof myBlob ?
payload :
new myBlob([payload], {
type: mimeType
});
function dataUrlToBlob(strUrl) {
var parts = strUrl.split(/[:;,]/),
type = parts[1],
decoder = parts[2] == "base64" ? atob : decodeURIComponent,
binData = decoder(parts.pop()),
mx = binData.length,
i = 0,
uiArr = new Uint8Array(mx);
for (i; i < mx; ++i) uiArr[i] = binData.charCodeAt(i);
return new myBlob([uiArr], {
type: type
});
}
function saver(url, winMode) {
if ('download' in anchor) { //html5 A[download]
anchor.href = url;
anchor.setAttribute("download", fileName);
anchor.className = "download-js-link";
anchor.innerHTML = "downloading...";
anchor.style.display = "none";
document.body.appendChild(anchor);
setTimeout(function() {
anchor.click();
document.body.removeChild(anchor);
if (winMode === true) {
setTimeout(function() {
self.URL.revokeObjectURL(anchor.href);
}, 250);
}
}, 66);
return true;
}
// handle non-a[download] safari as best we can:
if (/(Version)\/(\d+)\.(\d+)(?:\.(\d+))?.*Safari\//.test(navigator.userAgent)) {
url = url.replace(/^data:([\w\/\-\+]+)/, defaultMime);
if (!window.open(url)) { // popup blocked, offer direct download:
if (confirm("Displaying New Document\n\nUse Save As... to download, then click back to return to this page.")) {
location.href = url;
}
}
return true;
}
//do iframe dataURL download (old ch+FF):
var f = document.createElement("iframe");
document.body.appendChild(f);
if (!winMode) { // force a mime that will download:
url = "data:" + url.replace(/^data:([\w\/\-\+]+)/, defaultMime);
}
f.src = url;
setTimeout(function() {
document.body.removeChild(f);
}, 333);
} //end saver
if (navigator.msSaveBlob) { // IE10+ : (has Blob, but not a[download] or URL)
return navigator.msSaveBlob(blob, fileName);
}
if (self.URL) { // simple fast and modern way using Blob and URL:
saver(self.URL.createObjectURL(blob), true);
} else {
// handle non-Blob()+non-URL browsers:
if (typeof blob === "string" || blob.constructor === toString) {
try {
return saver("data:" + mimeType + ";base64," + self.btoa(blob));
} catch (y) {
return saver("data:" + mimeType + "," + encodeURIComponent(blob));
}
}
// Blob but not URL support:
reader = new FileReader();
reader.onload = function(e) {
saver(this.result);
};
reader.readAsDataURL(blob);
}
return true;
}; /* end download() */
}));
let Covid19Data = function() {
this.aFiles = ["Confirmed", "Deaths", "Recovered"];
let aLoaded = [];
this.mData = {};
this.oGeoJson = new ol.format.GeoJSON();
for (let sFile of this.aFiles) {
aLoaded.push(this.loadCsv(sFile));
}
this._dataLoaded = Promise.all(aLoaded);
};
Covid19Data.prototype.dataLoaded = function() {
return this._dataLoaded;
};
Covid19Data.prototype.loadCsv = function(sFile) {
fetch("COVID-19/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-" + sFile + ".csv")
.then((oResponse) => oResponse.text())
.then((sText) => {
let aLines = sText.split(/\r?\n/).map((sLine) => this.CSVtoArray(sLine));
let aHeader = aLines.shift();
this.mData[sFile] = [];
for (let aLine of aLines) {
// skip empty lines
if (!aLine) {
continue;
}
let mLine = {};
for (let i = 0; i < aHeader.length; i++) {
mLine[aHeader[i]] = aLine[i];
}
this.mData[sFile].push(mLine);
}
});
};
Covid19Data.prototype.CSVtoArray = function(text) {
var re_valid = /^\s*(?:'[^'\\]*(?:\\[\S\s][^'\\]*)*'|"[^"\\]*(?:\\[\S\s][^"\\]*)*"|[^,'"\s\\]*(?:\s+[^,'"\s\\]+)*)\s*(?:,\s*(?:'[^'\\]*(?:\\[\S\s][^'\\]*)*'|"[^"\\]*(?:\\[\S\s][^"\\]*)*"|[^,'"\s\\]*(?:\s+[^,'"\s\\]+)*)\s*)*$/;
var re_value = /(?!\s*$)\s*(?:'([^'\\]*(?:\\[\S\s][^'\\]*)*)'|"([^"\\]*(?:\\[\S\s][^"\\]*)*)"|([^,'"\s\\]*(?:\s+[^,'"\s\\]+)*))\s*(?:,|$)/g;
// Return NULL if input string is not well formed CSV string.
if (!re_valid.test(text)) return null;
var a = []; // Initialize array to receive values.
text.replace(re_value, // "Walk" the string using replace with callback.
function(m0, m1, m2, m3) {
// Remove backslash from \' in single quoted values.
if (m1 !== undefined) a.push(m1.replace(/\\'/g, "'"));
// Remove backslash from \" in double quoted values.
else if (m2 !== undefined) a.push(m2.replace(/\\"/g, '"'));
else if (m3 !== undefined) a.push(m3);
return ''; // Return empty string.
});
// Handle special case of empty last value.
if (/,\s*$/.test(text)) a.push('');
return a;
};
Covid19Data.prototype.mapDataToCountries = function(oCountrySource) {
for (let sFile of this.aFiles) {
for (let oData of this.mData[sFile]) {
let aCountry = oCountrySource.getFeaturesAtCoordinate(ol.proj.transform([parseFloat(oData.Long), parseFloat(oData.Lat)], "EPSG:4326", "EPSG:3857"));
if (aCountry.length > 0) {
let oCountry = aCountry[0]
let oOldProperties = oCountry.getProperties();
for (let sProperty in oData) {
let sPropertyName = sFile + "_" + sProperty;
if (sPropertyName in oOldProperties && sProperty.match(/^\d/)) {
oOldProperties[sPropertyName] += parseInt(oData[sProperty]);
} else if (sProperty.match(/^\d/)) {
oOldProperties[sPropertyName] = parseInt(oData[sProperty]);
} else {
oOldProperties[sPropertyName] = oData[sProperty];
}
}
oCountry.setProperties(oOldProperties);
} else {
console.log("Did not found country for: " + oData["Country/Region"] + " " + oData["Province/State"]);
}
}
}
};
let oCovid19Data = new Covid19Data();
oCovid19Data.dataLoaded().then(() => {
let sNewestData;
let fnDefaultStyleFunction = new ol.layer.Vector().getStyleFunction();
let oCountrySource = new ol.source.Vector({
"format": oCovid19Data.oGeoJson,
"url": "geo-countries/data/countries.geojson"
});
let fnStyle = function(oFeature, fResolution) {
let oFeatureData = oFeature.getProperties();
if (sNewestData === undefined) {
let oNewestDate = new Date();
do {
sNewestData = "Confirmed_" + oNewestDate.toLocaleDateString('en-US', {
"year": "2-digit",
"month": "numeric",
"day": "numeric"
});
oNewestDate.setDate(oNewestDate.getDate() - 1);
} while ((!(sNewestData in oFeatureData)) && sNewestData !== "Confirmed_1/22/20")
}
let sData = oFeatureData[sNewestData];
if (sData) {
let iRed = Math.min(255, Math.round(parseFloat(sData) / 10000 * 255));
return new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(' + iRed + ',0,0,0.4)'
}),
stroke: new ol.style.Stroke({
color: '#' + (iRed < 17 ? "0" : "") + iRed.toString(16) + '0000',
width: 1.25
})
});
} else {
return fnDefaultStyleFunction(oFeature, fResolution);
}
};
let i = 0;
oCountrySource.on("addfeature", function(oFeature) {
i++;
// all countries loaded
if (254 == i) {
oCovid19Data.mapDataToCountries(oCountrySource);
}
});
var DownloadGeoJSON = /*@__PURE__*/ (function(Control) {
function DownloadGeoJSON(opt_options) {
var options = opt_options || {};
var button = document.createElement('button');
button.innerHTML = 'G';
var element = document.createElement('div');
element.className = 'ol-unselectable ol-control';
element.style.top = "65px";
element.style.left = "0.5em";
element.appendChild(button);
Control.call(this, {
element: element,
target: options.target
});
button.addEventListener('click', this.handleDownloadGeoJSON.bind(this), false);
}
if (Control) DownloadGeoJSON.__proto__ = Control;
DownloadGeoJSON.prototype = Object.create(Control && Control.prototype);
DownloadGeoJSON.prototype.constructor = DownloadGeoJSON;
DownloadGeoJSON.prototype.handleDownloadGeoJSON = function handleDownloadGeoJSON() {
let aCollection = [];
fetch("simulation/COVID19_Simulation.json").then((o) => o.json()).then((oSimulation) => {
let mMaxRegion = {};
for (let sFile of oCovid19Data.aFiles) {
for (let oFeature of oCountrySource.getFeatures()) {
let mProperties = oFeature.getProperties();
for (let sProperty in mProperties) {
let oMatch = new RegExp("^" + sFile + "_(.*)");
let bMatch = oMatch.test(sProperty);
let sDate = RegExp.$1;
if (bMatch && sDate.match(/(\d?\d)\/(\d?\d)\/(\d\d)/) && mProperties[sProperty] > 0) {
try {
let aCoordinates = ol.extent.getCenter(oFeature.getGeometry().getExtent());
let dDate = new Date(2000 + parseInt(RegExp.$3), (parseInt(RegExp.$1) - 1), parseInt(RegExp.$2));
if (!(mProperties["Confirmed_Country/Region"] in mMaxRegion) || mMaxRegion[mProperties["Confirmed_Country/Region"]] < dDate.getTime()) {
mMaxRegion[mProperties["Confirmed_Country/Region"]] = dDate.getTime();
}
let oNewFeature = new ol.Feature({
geometry: new ol.geom.Point(ol.proj.transform(aCoordinates, "EPSG:3857", "EPSG:4326")),
type: sFile,
country_region: mProperties["Confirmed_Country/Region"],
time: dDate,
value: mProperties[sProperty]
});
aCollection.push(oNewFeature);
} catch (e) {
console.log(e);
}
}
}
}
// Add simulated data to country
for (let oFeature of oCountrySource.getFeatures()) {
let mProperties = oFeature.getProperties();
let country_region = mProperties["Confirmed_Country/Region"];
if (country_region in oSimulation) {
for (let oSimulationPoint of oSimulation[country_region].deterministicTrajectory) {
if (oSimulationPoint.time > mMaxRegion[country_region]) {
let aCoordinates = ol.extent.getCenter(oFeature.getGeometry().getExtent());
let oNewFeature = new ol.Feature({
geometry: new ol.geom.Point(ol.proj.transform(aCoordinates, "EPSG:3857", "EPSG:4326")),
type: "Confirmed_Simulated",
country_region: country_region,
time: new Date(oSimulationPoint.time),
value: Math.round(oSimulationPoint.infectious.total)
});
aCollection.push(oNewFeature);
}
}
}
}
}
let sGeoJson = oCovid19Data.oGeoJson.writeFeatures(aCollection);
download(sGeoJson, "Covid19Data.geojson", "application/geo+json");
});
};
return DownloadGeoJSON;
}(ol.control.Control));
let aControls = ol.control.defaults().extend([new DownloadGeoJSON()]);
let oMap = new ol.Map({
controls: aControls,
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
new ol.layer.Vector({
source: oCountrySource,
style: fnStyle
})
],
view: new ol.View({
center: ol.proj.fromLonLat([37.41, 8.82]),
zoom: 4
})
});
let oSelect = new ol.interaction.Select();
oMap.addInteraction(oSelect);
oSelect.on('select', function(e) {
let aFeatures = e.target.getFeatures();
if (aFeatures.getLength() > 0) {
let oFeature = aFeatures.item(0);
let oProperties = oFeature.getProperties();
if (sNewestData in oProperties) {
alert(sNewestData + " " + oProperties[sNewestData]);
// console.log(fnStyle(oFeature));
}
}
});
});
</script>
</body>
</html>