forked from marcusraitner/COVID-19-Dashboard
-
Notifications
You must be signed in to change notification settings - Fork 0
/
covid-19-7-day-incidence-county.js
executable file
·1029 lines (845 loc) · 33.7 KB
/
covid-19-7-day-incidence-county.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
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Variables used by Scriptable.
// These must be at the very top of the file. Do not edit.
// icon-color: deep-gray; icon-glyph: magic;
// Licence: GNU GENERAL PUBLIC LICENSE, Version 3, 29 June 2007
// Author: Marcus Raitner (https://fuehrung-erfahren.de)
// Source: https://github.com/marcusraitner/COVID-19-Dashboard
// Version: 1.8.0b
// ## Changelog
// * 1.0.1: Correction of layout of label for covid-beds
// * 1.0.2: Bug-Fix for Saar-Pfalz-Kreis (using GEN instead of county for join)
// * 1.0.3: Bug-Fix for Landsberg a. Lech (now using both GEN and county)
// * 1.0.4: Bug-Fix. Now using AGS for join (county and GEN only as backup)
// * 1.1.0: New API for vaccinations
// * 1.2.0: New colors and a new step for incidence 165
// * 1.3.0: New feature: Show also incidence for Germany with "showGermanyValue = true"
// * 1.4.0: New feature: R-Value for Germany. Bugfix for date of incidence
// * 1.5.0: Handling of parameters enhanced; see README for full reference
// * 1.6.0: New feature: Use frozen values of RKI
// * 1.7.0: New feature: Show one decimal (optional); improved rounding; minor visual improvements.
// * 1.8.0: Complete redesign of incidence graph and some minor adjustments
const version = "1.9.0b3"
//------------------------------------------------------------------------------
// General Options Section
//------------------------------------------------------------------------------
// Set to true for debugging information in the console
const debug = false;
// Set to true for an image background, false for no image.
const imageBackground = false;
// Set to true to reset the widget's background image.
const forceImageUpdate = false;
// Show also the incidence for Germany in total
// var showGermanyValue = false;
var showGermanyValue = true;
// Show also the R-Value (only if showGermanyValue == true)
var showRValue = true;
// Toggle showing of vaccination status
// var showVaccination = true;
var showVaccination = false;
// Toggle showing of ICU beds
var showIcu = true;
// show daily portion of incidence
var showDaily = true;
// Show frozen value for incidence instead of calculating it.
var useFrozen = false;
// number of days to show in detail
// var detail = 5;
var detail = 8;
// show values for the state
var showBl = true;
// the color theme
var theme = "original";
// palette found here: https://coolors.co/03071e-370617-6a040f-9d0208-d00000-dc2f02-e85d04-f48c06-faa307-ffba08
const incidenceColors = {
original: [{
lower: 0,
// color: new Color('#b1a7a6', 1),
color: new Color('#999999', 1),
highlight: new Color("#FFFFFF", .7)
},
{
lower: 35,
color: new Color('#F48C06', 1),
highlight: new Color("#FFFFFF", .7)
},
{
lower: 50,
color: new Color('#E85D04', 1),
highlight: new Color("#FFFFFF", .7)
},
{
lower: 100,
color: new Color('#D00000', 1),
highlight: new Color("#FFFFFF", .7)
},
{
lower: 165,
color: new Color('#6A040F', 1),
highlight: new Color("#FFFFFF", .7)
},
{
lower: 200,
color: new Color('#370617', 1),
highlight: new Color("#FFFFFF", .7)
}
],
rki: [{
lower: 0,
color: new Color('#ffffff', 1),
highlight: new Color('#000000', .5)
},
{
lower: 5,
color: new Color('#fcf39f', 1),
highlight: new Color('#000000', .5)
},
{
lower: 25,
color: new Color('#f9af4d', 1),
highlight: new Color("#FFFFFF", .7)
},
{
lower: 50,
color: new Color('#ff3d33', 1),
highlight: new Color("#FFFFFF", .7)
},
{
lower: 100,
color: new Color('#cc0a00', 1),
highlight: new Color("#FFFFFF", .7)
},
{
lower: 250,
color: new Color('#8c0801', 1),
highlight: new Color("#FFFFFF", .7)
},
{
lower: 500,
color: new Color('#f202ca', 1),
highlight: new Color("#FFFFFF", .7)
}
]
};
// colors for covid beds highlighting
const colorCovidBed = new Color('#DC2F02', 1);
const colorCovidBedVentilation = new Color('#9D0208', 1);
const bedsLineColor = new Color('#b1a7a6', 1);
const bedsLineFreeColor = new Color('#4D8802', 1);
// other colors
const accentColor2 = Color.lightGray(); // used for weekends
const vaccinationColor = new Color('#00848C', 1);
const vaccinationBoosterColor = new Color('#004156', 1);
// Gradients
let vaccinationGradient = new LinearGradient();
vaccinationGradient.locations = [0, 0.2, 0.8, 1];
// vaccinationGradient.colors = [
// new Color('#8C8C8C', 1),
// new Color('#535353', 1),
// new Color('#535353', 1),
// new Color('#8C8C8C', 1)
//
// ];
vaccinationGradient.colors = [
new Color('#444444', 1),
new Color('#444444', 1),
new Color('#444444', 1),
new Color('#444444', 1)
];
let backgroundGradient = new LinearGradient();
backgroundGradient.locations = [0, 0.2, 0.8, 1];
// backgroundGradient.colors = [
// new Color("#28416F"),
// new Color("#141E30"),
// new Color("#141E30"),
// new Color("#28416F")
// ];
backgroundGradient.colors = [
new Color("#000000"),
new Color("#000000"),
new Color("#000000"),
new Color("#000000")
];
//------------------------------------------------------------------------------
const DAY_IN_MICROSECONDS = 86400000;
const widgetHeight = 338;
const widgetWidth = 720;
const graphLow = 0;
var graphHeight = 175;
var graphWidth = widgetWidth;
const bedsHeight = 80;
var bedsWidth = graphWidth;
const bedsLineWidth = 12;
const tickWidth = 4;
const vaccinationWidth = 65;
// const smallSpace = 12;
const smallSpace = 12.4;
const gap = 3;
var spaceBetweenDays = smallSpace * 5;
var vertLineWeight = spaceBetweenDays - gap;
const smallLineWeight = smallSpace - gap;
// APIs
const apiUrl = (location) => `https://services7.arcgis.com/mOBPykOjAyBO2ZKk/arcgis/rest/services/RKI_Landkreisdaten/FeatureServer/0/query?where=1%3D1&outFields=GEN,AGS,EWZ,EWZ_BL,cases,death_rate,deaths,cases7_per_100k,cases7_bl_per_100k,BL,county&geometry=${ location.longitude.toFixed( 3 ) }%2C${ location.latitude.toFixed( 3 ) }&geometryType=esriGeometryPoint&inSR=4326&spatialRel=esriSpatialRelWithin&returnGeometry=false&outSR=4326&f=json`;
const apiUrlData = (county, minDate) => `https://services7.arcgis.com/mOBPykOjAyBO2ZKk/arcgis/rest/services/Covid19_RKI_Sums/FeatureServer/0/query?where=Landkreis+LIKE+%27%25${ encodeURIComponent( county ) }%25%27+AND+Meldedatum+%3E+%27${ encodeURIComponent( minDate ) }%27&objectIds=&time=&resultType=none&outFields=*&returnIdsOnly=false&returnUniqueIdsOnly=false&returnCountOnly=false&returnDistinctValues=false&cacheHint=false&orderByFields=Meldedatum&groupByFieldsForStatistics=&outStatistics=&having=&resultOffset=&resultRecordCount=&sqlFormat=none&f=json&token=`;
const apiUrlData2 = (ags, minDate) => `https://services7.arcgis.com/mOBPykOjAyBO2ZKk/arcgis/rest/services/Covid19_RKI_Sums/FeatureServer/0/query?where=idLandkreis%3D+${ encodeURIComponent( ags ) }+AND+Meldedatum+%3E+%27${ encodeURIComponent( minDate ) }%27&objectIds=&time=&resultType=none&outFields=*&returnIdsOnly=false&returnUniqueIdsOnly=false&returnCountOnly=false&returnDistinctValues=false&cacheHint=false&orderByFields=Meldedatum&groupByFieldsForStatistics=&outStatistics=&having=&resultOffset=&resultRecordCount=&sqlFormat=none&f=json&token=`;
const diviApiUrl = (location) => `https://services7.arcgis.com/mOBPykOjAyBO2ZKk/arcgis/rest/services/DIVI_Intensivregister_Landkreise/FeatureServer/0/query?where=1%3D1&outFields=*&geometry=${ location.longitude.toFixed( 3 ) }%2C${ location.latitude.toFixed( 3 ) }&geometryType=esriGeometryPoint&inSR=4326&spatialRel=esriSpatialRelWithin&returnGeometry=false&outSR=4326&f=json`;
const vaccUrl = `https://api.corona-zahlen.org/vaccinations`;
const germanyUrl = `https://api.corona-zahlen.org/germany`;
const apiUrlDistricts = `https://api.corona-zahlen.org/districts/`;
const apiUrlDataFrozen = (ags, days) => `https://api.corona-zahlen.org/districts/${ encodeURIComponent( ags ) }/history/frozen-incidence/${ encodeURIComponent( days ) }`;
const stateToAbbr = {
'Baden-Württemberg': 'BW',
'Bayern': 'BY',
'Berlin': 'BE',
'Brandenburg': 'BB',
'Bremen': 'HB',
'Hamburg': 'HH',
'Hessen': 'HE',
'Mecklenburg-Vorpommern': 'MV',
'Niedersachsen': 'NI',
'Nordrhein-Westfalen': 'NW',
'Rheinland-Pfalz': 'RP',
'Saarland': 'SL',
'Sachsen': 'SN',
'Sachsen-Anhalt': 'ST',
'Schleswig-Holstein': 'SH',
'Thüringen': 'TH'
};
const rulesUrl = {
'Baden-Württemberg': 'https://www.baden-wuerttemberg.de/de/service/aktuelle-infos-zu-corona/',
'Bayern': 'https://www.bayern.de/coronavirus-in-bayern-informationen-auf-einen-blick/',
'Berlin': 'https://www.berlin.de/corona/',
'Brandenburg': 'https://kkm.brandenburg.de/kkm/de/',
'Bremen': 'https://www.bremen.de/corona',
'Hamburg': 'https://www.hamburg.de/coronavirus/',
'Hessen': 'https://www.hessen.de/fuer-buerger/aktuelle-informationen-zu-corona-hessen',
'Mecklenburg-Vorpommern': 'https://www.regierung-mv.de/corona/',
'Niedersachsen': 'https://www.niedersachsen.de/Coronavirus',
'Nordrhein-Westfalen': 'https://www.land.nrw/corona',
'Rheinland-Pfalz': 'https://corona.rlp.de/de/startseite/',
'Saarland': 'https://corona.saarland.de/DE/home/home_node.html',
'Sachsen': 'https://www.coronavirus.sachsen.de/index.html',
'Sachsen-Anhalt': 'https://coronavirus.sachsen-anhalt.de/',
'Schleswig-Holstein': 'https://www.schleswig-holstein.de/DE/Schwerpunkte/Coronavirus/coronavirus_node.html;jsessionid=8651006488D177B24833E4A56502FC06.delivery1-master',
'Thüringen': 'https://corona.thueringen.de/'
};
let widget = await createWidget();
await widget.presentMedium();
Script.setWidget(widget);
Script.complete();
async function createWidget(items) {
let location;
const list = new ListWidget();
// If it's an image background, display it.
if (imageBackground) {
// Determine if our image exists and when it was saved.
const files = FileManager.local()
const path = files.joinPath(files.documentsDirectory(), "covid19-background-image")
const exists = files.fileExists(path)
// If it exists and an update isn't forced, use the cache.
if (exists && (config.runsInWidget || !forceImageUpdate)) {
list.backgroundImage = files.readImage(path)
// If it's missing when running in the widget, use a gray background.
} else if (!exists && config.runsInWidget) {
list.backgroundGradient = backgroundGradient;
// But if we're running in app, prompt the user for the image.
} else {
const img = await Photos.fromLibrary()
list.backgroundImage = img
files.writeImage(path, img)
}
// If it's not an image background, show the gradient.
} else {
list.backgroundGradient = backgroundGradient;
}
list.setPadding(0, 0, 0, 0);
// Parse parameters
if (args.widgetParameter) {
const params = args.widgetParameter.split(';');
for (var i = 0; i < params.length; i++) {
const p = params[i].split('=');
if (p[0].trim().toLowerCase() == "loc") {
const fixedCoordinates = p[1].split(',').map(parseFloat);
location = {
latitude: fixedCoordinates[0],
longitude: fixedCoordinates[1]
};
} else if (p[0].trim().toLowerCase() == "de") {
if (p[1].trim().toLowerCase() == "y") {
showGermanyValue = true;
} else {
showGermanyValue = false;
}
} else if (p[0].trim().toLowerCase() == "bl") {
if (p[1].trim().toLowerCase() == "y") {
showBl = true;
} else {
showBl = false;
}
} else if (p[0].trim().toLowerCase() == "rval") {
if (p[1].trim().toLowerCase() == "y") {
showRValue = true;
} else {
showRValue = false;
}
} else if (p[0].trim().toLowerCase() == "vac") {
if (p[1].trim().toLowerCase() == "y") {
showVaccination = true;
} else {
showVaccination = false;
}
} else if (p[0].trim().toLowerCase() == "beds") {
if (p[1].trim().toLowerCase() == "y") {
showIcu = true;
} else {
showIcu = false;
}
} else if (p[0].trim().toLowerCase() == "daily") {
if (p[1].trim().toLowerCase() == "y") {
showDaily = true;
} else {
showDaily = false;
}
} else if (p[0].trim().toLowerCase() == "frozen") {
if (p[1].trim().toLowerCase() == "y") {
useFrozen = true;
} else {
useFrozen = false;
}
} else if (p[0].trim().toLowerCase() == "theme") {
if (p[1].trim().toLowerCase() == "rki") {
theme = "rki";
} else {
theme = "original";
}
} else if (p[0].trim().toLowerCase() == "days") {
const parsed = Number.parseInt(p[1].trim());
if (!Number.isNaN(parsed)) {
detail = parsed;
}
} else if (p.length == 1) {
// for compatability with old syntax
const fixedCoordinates = p[0].split(',').map(parseFloat);
location = {
latitude: fixedCoordinates[0],
longitude: fixedCoordinates[1]
};
}
}
}
// Adjust dimensions
// get data for the last days
var days = 18;
if (showGermanyValue) {
days -= 1;
}
if (showBl) {
days -= 1;
}
if (showVaccination) {
graphWidth = widgetWidth - vaccinationWidth - 10;
days -= 1;
} else {
graphWidth = widgetWidth;
}
if (detail < 0) {
detail = 0;
}
if (detail > days - 7) {
detail = days - 7;
}
// calculate days for showing history
days = (days - detail - 7) * (spaceBetweenDays / smallSpace) + detail + 9;
if (!showBl && !showGermanyValue) {
days += 2;
}
if (!showVaccination) {
days += 1;
}
if (showIcu) {
bedsWidth = graphWidth;
} else {
graphHeight += bedsHeight;
}
if (!location) {
Location.setAccuracyToThreeKilometers();
try {
location = await Location.current();
if (debug) {
console.log('get current lat/lon');
}
} catch (e) {
errorText = list.addText('Keine Ortsdaten gefunden');
errorText.textColor = Color.white();
return list;
}
}
var germanyData = null;
if (showGermanyValue) {
if (debug) {
console.log("Getting data for Germany: " + germanyUrl);
}
germanyData = await new Request(germanyUrl).loadJSON();
if (debug) {
console.log(germanyData);
}
}
if (debug) {
console.log("Getting info for location: " + apiUrl(location));
}
// get data for current location
const locationData = await new Request(apiUrl(location)).loadJSON();
if (debug) {
console.log(locationData);
}
if (!locationData || !locationData.features || !locationData.features.length) {
errorText = list.addText('Keine Ergebnisse für den aktuellen Ort gefunden.');
errorText.textColor = Color.white();
console.log(locationData)
return list;
}
const attr = locationData.features[0].attributes;
// extract information needed
const cityName = attr.GEN; // name of 'Landkreis'
const ewz = attr.EWZ / 100000; // number of inhabitants
const ewzBL = attr.EWZ_BL
const county = attr.county; // Landkreis
const gen = attr.GEN;
var ags = attr.AGS;
const bundesLand = stateToAbbr[attr.BL];
const bl = attr.BL;
const incidenceBl = roundIncidence(attr.cases7_bl_per_100k);
const latestIncidence = attr.cases7_per_100k;
const date = new Date();
date.setTime(date.getTime() - days * DAY_IN_MICROSECONDS);
const minDate = ('0' + (date.getMonth() + 1)).slice(-2) + '-' + ('0' + date.getDate()).slice(-2) + '-' + date.getFullYear();
let countyData;
let updated;
if (useFrozen) {
if (!ags) {
if (debug) {
console.log("ags not set,looking it up with: " + apiUrlDistricts);
}
const districts = await new Request(apiUrlDistricts).loadJSON();
if (debug) {
console.log(districts);
}
for (var district in districts.data) {
if (districts.data[district].county == county) {
ags = districts.data[district].ags;
if (debug) {
console.log("Found ags: " + ags);
}
break;
}
}
}
if (debug) {
console.log("Getting frozen data for ags: " + apiUrlDataFrozen(ags, days));
}
countyData = await new Request(apiUrlDataFrozen(ags, days - 7)).loadJSON();
if (debug) {
console.log(countyData);
}
if (!countyData || !countyData.data || !countyData.data[ags].history || !countyData.data[ags].history.length) {
list.addText('Keine Statistik gefunden.');
return list;
}
updated = new Date(countyData.meta.lastUpdate);
} else {
if (ags) {
if (debug) {
console.log("Getting data for ags: " + apiUrlData2(ags, minDate));
}
countyData = await new Request(apiUrlData2(ags, minDate)).loadJSON();
if (debug) {
console.log(countyData);
}
} else {
if (debug) {
console.log("Getting data for county: " + apiUrlData(gen, minDate));
}
countyData = await new Request(apiUrlData(gen, minDate)).loadJSON();
if (debug) {
console.log(countyData);
}
if (!countyData || !countyData.features || !countyData.features.length) {
if (debug) {
console.log("Getting data for county: " + apiUrlData(county, minDate));
}
countyData = await new Request(apiUrlData(county, minDate)).loadJSON();
if (debug) {
console.log(countyData);
}
}
}
if (!countyData || !countyData.features || !countyData.features.length) {
list.addText('Keine Statistik gefunden.');
return list;
}
tmp = countyData.features[0].attributes.Datenstand.replace(" Uhr", "").split(",");
tmpDate = tmp[0].split(".");
tmpTime = tmp[1].split(":");
updated = new Date(tmpDate[2], tmpDate[1] - 1, tmpDate[0], tmpTime[0], tmpTime[1]);
}
let stack = list.addStack();
stack.layoutHorizontally();
stack.setPadding(0, 0, 0, 0);
let leftStack = stack.addStack();
leftStack.layoutVertically();
let incidenceText = leftStack.addText('🦠 7-Tage-Inzidenz'.toUpperCase() + ' – ' + county);
incidenceText.font = Font.semiboldRoundedSystemFont(11);
incidenceText.textColor = Color.white();
incidenceText.url = rulesUrl[attr.BL];
if (showVaccination) {
leftStack.addSpacer(5);
if (debug) {
console.log("Getting vaccination data: " + vaccUrl);
}
const vaccData = await new Request(vaccUrl).loadJSON();
if (debug) {
console.log(vaccData);
}
if (!vaccData) {
list.addText('Kein Impfstatus gefunden.');
return list;
}
let quoteInitial = Math.round(vaccData.data.states[bundesLand].quote * 100);
let quoteBooster = Math.round(vaccData.data.states[bundesLand].secondVaccination.quote * 100);
leftStack.setPadding(7, 7, 2, 0);
stack.addSpacer(10);
let rightStack = stack.addStack();
rightStack.setPadding(0, 0, 0, 0);
rightStack.backgroundGradient = vaccinationGradient;
rightStack.cornerRadius = 4;
// Add vaccination status
const vaccinationHeight = widgetHeight - 10;
const vaccinationBottom = vaccinationHeight;
const vaccinationBarWidth = 20;
let drawContext = new DrawContext();
drawContext.size = new Size(vaccinationWidth, vaccinationHeight);
drawContext.opaque = false;
let vaccinationTextRect = new Rect(10, 15, vaccinationWidth - 10, 55);
drawTextR(drawContext, '💉', vaccinationTextRect, Color.white(), Font.mediumSystemFont(40));
vaccinationTextRect = new Rect(6, 5, vaccinationWidth - 10, 25);
drawTextR(drawContext, bundesLand, vaccinationTextRect, Color.white(), Font.mediumSystemFont(22));
let vaccinationRect = new Rect(0, (1 - quoteInitial / 100) * vaccinationBottom, vaccinationWidth, vaccinationBottom * quoteInitial / 100);
drawRoundedRect(drawContext, vaccinationRect, vaccinationColor, 4);
vaccinationTextRect = new Rect(10, (1 - quoteInitial / 100) * vaccinationBottom - 26, vaccinationWidth, 22);
drawTextR(drawContext, quoteInitial + ' %', vaccinationTextRect, Color.white(), Font.regularSystemFont(22));
let vaccinationBoosterRect = new Rect(0, (1 - quoteBooster / 100) * vaccinationBottom, vaccinationWidth, vaccinationBottom * quoteBooster / 100);
drawRoundedRect(drawContext, vaccinationBoosterRect, vaccinationBoosterColor, 4);
vaccinationTextRect = new Rect(10, (1 - quoteBooster / 100) * vaccinationBottom - 26, vaccinationWidth, 22);
drawTextR(drawContext, quoteBooster + ' %', vaccinationTextRect, Color.white(), Font.regularSystemFont(22));
drawLine(drawContext, new Point(1, 0), new Point(1, vaccinationHeight), 2, Color.lightGray());
rightStack.addImage(drawContext.getImage());
} else {
leftStack.setPadding(7, 7, 2, 7);
}
let min, max, diff;
let dailyValues = new Array();
let history = new Array();
if (useFrozen) {
history = countyData.data[ags].history;
// add the latest incidence in case if we miss the value for today
if (!isToday(new Date(history[history.length - 1].date))) {
const today = {
weekIncidence: latestIncidence,
date: new Date()
};
history.push(today);
}
} else {
for (let i = countyData.features.length - 1; i >= 6; i--) {
dailyValues[i - 6] = {
abs: countyData.features[i].attributes.AnzahlFall,
rel: countyData.features[i].attributes.AnzahlFall / ewz
};
let sum = 0;
for (let j = 0; j < 7; j++) {
sum += countyData.features[i - j].attributes.AnzahlFall;
}
sum /= ewz;
history[i - 6] = {
weekIncidence: sum,
date: countyData.features[i].attributes.Meldedatum
};
}
}
for (let i = 0; i < history.length; i++) {
history[i].weekIncidence = roundIncidence(history[i].weekIncidence);
let aux = history[i].weekIncidence;
max = (aux > max || max == undefined ? aux : max);
}
if (incidenceBl > max) {
max = incidenceBl;
}
if (showGermanyValue && germanyData.weekIncidence > max) {
max = germanyData.weekIncidence;
}
min = 0;
diff = max - min;
let graphDrawContext = new DrawContext();
graphDrawContext.size = new Size(graphWidth, graphHeight);
graphDrawContext.opaque = false;
graphDrawContext.setFont(Font.mediumSystemFont(20));
graphDrawContext.setTextAlignedCenter();
const graphTop = 23;
const graphBottom = graphHeight - 23;
const barHeight = graphBottom - graphTop;
let dayColor;
for (let i = 0; i < history.length; i++) {
let date = new Date(history[i].date);
if (!useFrozen) {
date.setDate(date.getDate() + 1);
}
const day = date.getDate();
const dayOfWeek = date.getDay();
const cases = history[i].weekIncidence;
const delta = (cases - min) / diff;
let drawColor;
let highlight;
if (dayOfWeek == 0 || dayOfWeek == 6) {
dayColor = accentColor2;
} else {
dayColor = Color.white();
}
// Draw bar
cols = getColor(cases);
drawColor = cols.color;
highlight = cols.highlight;
let x0;
let barWidth;
if (i < history.length - detail) {
x0 = smallSpace * i;
barWidth = smallLineWeight;
} else {
x0 = smallSpace * (history.length - detail) + spaceBetweenDays * (i - history.length + detail);
barWidth = vertLineWeight;
}
let rect = new Rect(x0, graphBottom - (barHeight * delta), barWidth, barHeight * delta);
drawRoundedRect(graphDrawContext, rect, drawColor, 2);
let y = graphBottom;
// draw daily cases (if set)
if (showDaily && !useFrozen && i < history.length - 1) {
const dailyDelta = (dailyValues[i + 1].rel - min) / diff;
y -= barHeight * dailyDelta;
rect = new Rect(x0, y, barWidth, barHeight * dailyDelta);
drawRoundedRect(graphDrawContext, rect, highlight, 2);
if (i >= history.length - detail) {
// y -= 21;
y -= 25;
rect = new Rect(x0, y, barWidth, 20);
// drawTextR(graphDrawContext, "+" + dailyValues[i + 1].abs, rect, highlight, Font.mediumSystemFont(18));
drawTextR(graphDrawContext, "+" + dailyValues[i + 1].abs, rect, highlight, Font.mediumSystemFont(20));
}
}
// Draw labels
if (i < history.length - detail) {
if (dayOfWeek == 0 && i > 0 && i < history.length - detail - 1) {
const dayRect = new Rect(x0 - smallSpace, graphBottom + 1, 3 * smallSpace, 23);
drawTextR(graphDrawContext, day, dayRect, dayColor, Font.mediumSystemFont(20));
}
} else {
let y1 = graphBottom - (barHeight * delta) - 28 + 23;
if (y1 > y) {
y1 = y;
}
const casesRect = new Rect(x0, y1 - 23, barWidth, 23);
drawTextR(graphDrawContext, formatIncidence(cases), casesRect, dayColor, Font.mediumSystemFont(20));
const dayRect = new Rect(x0, graphBottom + 1, barWidth, 23);
drawTextR(graphDrawContext, day, dayRect, dayColor, Font.mediumSystemFont(20));
}
}
// Draw bar for Germany
if (showGermanyValue) {
germanyData.weekIncidence = roundIncidence(germanyData.weekIncidence);
const delta = (germanyData.weekIncidence - min) / diff;
const y = graphBottom - (barHeight * delta);
const x = graphWidth - vertLineWeight;
// draw rect in grey
let rect = new Rect(x, y, vertLineWeight, barHeight * delta);
drawRoundedRect(graphDrawContext, rect, new Color("#6c757d", 1), 2);
// draw border in color of incidence
drawColor = getColor(germanyData.weekIncidence).color;
rect = new Rect(x + 2, y + 2, vertLineWeight - 4, barHeight * delta - 4);
let path = new Path();
path.addRoundedRect(rect, 2, 2);
graphDrawContext.addPath(path);
graphDrawContext.setLineWidth(4);
graphDrawContext.setStrokeColor(drawColor);
graphDrawContext.strokePath();
// draw labels
const bundesLandRect = new Rect(x, graphBottom - 28, vertLineWeight, 23);
drawTextR(graphDrawContext, "DE", bundesLandRect, dayColor, Font.mediumSystemFont(20));
const bundesLandIncidenceRect = new Rect(x, y - 28, vertLineWeight, 23);
drawTextR(graphDrawContext, formatIncidence(germanyData.weekIncidence), bundesLandIncidenceRect, dayColor, Font.mediumSystemFont(20));
// draw R-value (if set)
if (showRValue) {
let rRect = new Rect(x - 20, graphBottom + 1, vertLineWeight + 20, 23);
drawTextR(graphDrawContext, "R:" + Intl.NumberFormat('de-DE', {
minimumFractionDigits: 2
}).format(germanyData.r.value), rRect, dayColor, Font.mediumSystemFont(20));
}
}
// Now draw the bar for the Bundesland
if (showBl) {
const delta = (incidenceBl - min) / diff;
const y = graphBottom - (barHeight * delta);
const x = (showGermanyValue ? graphWidth - vertLineWeight - spaceBetweenDays : graphWidth - vertLineWeight);
// draw bar in grey
let rect = new Rect(x, y, vertLineWeight, barHeight * delta);
drawRoundedRect(graphDrawContext, rect, new Color("#343a40", 1), 2);
// draw border in color of incidence
drawColor = getColor(incidenceBl).color;
rect = new Rect(x + 2, y + 2, vertLineWeight - 4, barHeight * delta - 4);
path = new Path();
path.addRoundedRect(rect, 2, 2);
graphDrawContext.addPath(path);
graphDrawContext.setLineWidth(4);
graphDrawContext.setStrokeColor(drawColor);
graphDrawContext.strokePath();
// Draw labels
const bundesLandRect = new Rect(x, graphBottom - 28, vertLineWeight, 23);
drawTextR(graphDrawContext, bundesLand, bundesLandRect, dayColor, Font.mediumSystemFont(20));
const bundesLandIncidenceRect = new Rect(x, y - 28, vertLineWeight, 23);
drawTextR(graphDrawContext, formatIncidence(incidenceBl), bundesLandIncidenceRect, dayColor, Font.mediumSystemFont(20));
}
let graphImage = graphDrawContext.getImage();
leftStack.addImage(graphImage);
leftStack.addSpacer(5);
if (showIcu) {
// Get data for icu beds
if (debug) {
console.log("Getting DIVI info for location: " + diviApiUrl(location));
}
// get data for ICU beds of current location
const diviLocationData = await new Request(diviApiUrl(location)).loadJSON();
if (debug) {
console.log(diviLocationData);
}
if (!diviLocationData || !diviLocationData.features || !diviLocationData.features.length) {
errorText = list.addText('Keine DIVI-Ergebnisse für den aktuellen Ort gefunden.');
errorText.textColor = Color.white();
console.log(diviLocationData);
return list;
}
const diviAttr = diviLocationData.features[0].attributes;
// extract data needed
const freeBeds = (!diviAttr.betten_frei ? 0 : diviAttr.betten_frei);
const beds = (!diviAttr.betten_gesamt ? 0 : diviAttr.betten_gesamt);
const usedBeds = (!diviAttr.betten_belegt ? 0 : diviAttr.betten_belegt);
const cases = (!diviAttr.faelle_covid_aktuell ? 0 : diviAttr.faelle_covid_aktuell);
const casesBeatmet = (!diviAttr.faelle_covid_aktuell_beatmet ? 0 : diviAttr.faelle_covid_aktuell_beatmet);
drawContext = new DrawContext();
drawContext.size = new Size(bedsWidth, bedsHeight);
drawContext.opaque = false;
let freeBedsWidth = freeBeds / beds * bedsWidth;
let covidBedsWidth = cases / beds * bedsWidth;
let beatmetBedsWidth = casesBeatmet / beds * bedsWidth;
freeBedsWidth = (!freeBedsWidth ? tickWidth / 2 : freeBedsWidth);
covidBedsWidth = (!covidBedsWidth ? tickWidth / 2 : covidBedsWidth);
beatmetBedsWidth = (!beatmetBedsWidth ? tickWidth / 2 : beatmetBedsWidth);
// Line representing all beds
let bedsLineRect = new Rect(0, bedsHeight / 2 - bedsLineWidth / 2, bedsWidth, bedsLineWidth);
drawRoundedRect(drawContext, bedsLineRect, bedsLineColor, 2)
// let bedsRect = new Rect(0, bedsHeight / 2 - 40, bedsWidth - freeBedsWidth - 10, 26);
let bedsRect = new Rect(0, bedsHeight / 2 - 35, bedsWidth - freeBedsWidth - 10, 26);
drawContext.setFont(Font.mediumSystemFont(22));
drawContext.setTextColor(Color.white());
drawContext.drawTextInRect('🛏' + 'Intensivbetten'.toUpperCase() + ': ' + beds, bedsRect)
// Portion representing free beds
bedsLineRect = new Rect(bedsWidth - freeBedsWidth, bedsHeight / 2 - bedsLineWidth / 2, freeBedsWidth, bedsLineWidth);
drawRoundedRect(drawContext, bedsLineRect, bedsLineFreeColor, 2);
drawLine(drawContext, new Point(bedsWidth - freeBedsWidth, bedsHeight / 2 + bedsLineWidth / 2 + 5), new Point(bedsWidth - freeBedsWidth, bedsHeight / 2 - 40), tickWidth, new Color('#4D8802', 1));
drawContext.setFont(Font.mediumSystemFont(22));
let freeRect = new Rect(0, bedsHeight / 2 - 35, bedsWidth - freeBedsWidth - 10, 22);
drawContext.setTextAlignedRight();
if (freeBedsWidth > bedsWidth / 2) {
freeRect = new Rect(bedsWidth - freeBedsWidth + 10, bedsHeight / 2 - 35, freeBedsWidth - 10, 22);
drawContext.setTextAlignedLeft();
}
drawContext.drawTextInRect('frei'.toUpperCase() + ': ' + freeBeds, freeRect)
// Portion representing covid patients
bedsLineRect = new Rect(0, bedsHeight / 2 - bedsLineWidth / 2, covidBedsWidth, bedsLineWidth);
drawRoundedRect(drawContext, bedsLineRect, colorCovidBed, 2);
drawLine(drawContext, new Point(covidBedsWidth, bedsHeight / 2 - bedsLineWidth / 2 - 5), new Point(covidBedsWidth, bedsHeight / 2 + 38), tickWidth, colorCovidBed);
// Portion representing cases beatmet
bedsLineRect = new Rect(0, bedsHeight / 2 - bedsLineWidth / 2, beatmetBedsWidth, bedsLineWidth);
drawRoundedRect(drawContext, bedsLineRect, colorCovidBedVentilation, 2);
drawLine(drawContext, new Point(beatmetBedsWidth, bedsHeight / 2 - bedsLineWidth / 2 - 5), new Point(beatmetBedsWidth, bedsHeight / 2 + 20), tickWidth, colorCovidBedVentilation);
let covidRect = new Rect(covidBedsWidth + 10, bedsHeight / 2 + 10, bedsWidth - covidBedsWidth - 10, 22);
drawContext.setTextAlignedLeft();
if (covidBedsWidth > bedsWidth / 2) {
covidRect = new Rect(0, bedsHeight / 2 + 10, covidBedsWidth - 10, 22);
drawContext.setTextAlignedRight();
}
let c19Label = '🦠C19: ' + cases;
if (cases > 0) {
c19Label = c19Label + ' (davon ' + casesBeatmet + ' beatmet)'
}
drawContext.drawTextInRect(c19Label, covidRect);
leftStack.addImage(drawContext.getImage());
}
// leftStack.addSpacer(3);
let statusStack = leftStack.addStack();
statusStack.layoutHorizontally();
statusStack.setPadding(0, 0, 0, 0);
statusStack.addSpacer();
let statusText = statusStack.addText("Datenstand: " + new Intl.DateTimeFormat('de-DE', {
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric'
// }).format(updated) + " // Version: " + version);
}).format(updated));
statusText.font = Font.lightSystemFont(8);
statusText.textColor = Color.gray();
if (!showVaccination) {
statusStack.addSpacer();
}
return list;
}
function drawTextR(drawContext, text, rect, color, font) {
drawContext.setFont(font);
drawContext.setTextColor(color);
drawContext.drawTextInRect(new String(text).toString(), rect);
}
function drawLine(drawContext, point1, point2, width, color) {
const path = new Path();
path.move(point1);
path.addLine(point2);
drawContext.addPath(path);
drawContext.setStrokeColor(color);
drawContext.setLineWidth(width);
drawContext.strokePath();
}
function drawRoundedRect(drawContext, rect, color, radius) {
const path = new Path();
path.addRoundedRect(rect, radius, radius);
drawContext.addPath(path);
drawContext.setFillColor(color);
drawContext.fillPath();