-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.html
974 lines (849 loc) · 35.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
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
<!--
-- COVID-19 Data Visualization
-- @version 1.0.0
-- @author Faisal Zaman <300518055>
-- @author Kun Huang <300291127>
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Covid</title>
<!-- Custom fonts for this template-->
<link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
<link
href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i"
rel="stylesheet">
<link href="https://api.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.css" rel="stylesheet" />
<link href="css/sb-admin-2.min.css" rel="stylesheet">
<style>
.y-axis line {
opacity: .2;
}
.y-axis path {
display: none;
}
.line {
fill: none;
stroke-width: 1.5px;
opacity: .75;
}
.overlay {
fill: none;
pointer-events: all;
}
.lineHoverText {
text-shadow: -2px -2px 0 #fff, 2px -2px 0 #fff, -2px 2px 0 #fff, 2px 2px 0 #fff;
}
.hoverCircle {
opacity: .75;
}
.tableFixHead {
overflow-y: auto;
height: 100px;
}
.tableFixHead thead th {
position: sticky;
top: 0;
background-color: #fff;
}
.header {
background: #FAF250;
color: #24211B;
}
.header p span {
font-weight: 700;
}
.header_stat {
text-align: center;
}
.header_stat span {
font-weight: 700;
font-size: 25px;
display: block;
}
.header_stat {
text-align: center;
font-size: 18px;
font-weight: 200;
}
.colorplate {
background: linear-gradient(90deg, #F7F15C 0%, #F0C277 35%, #D76156 100%);
width: 110px;
height: 10px;
position: absolute;
right: 120px;
}
#map {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
.bubble {
fill-opacity: .7;
stroke: #3b3b3b;
stroke-width: 0.5px;
}
.d3-tooltip {
position: absolute;
z-index: 10;
visibility: hidden;
padding: 15px;
background: rgba(0, 0, 0, 0.6);
border-radius: 5px;
color: #fff;
}
.table-responsive {
height: 750px;
overflow-y: scroll;
overflow-x: hidden;
}
path.average {
stroke: darkviolet;
stroke-width: 1px;
fill: none;
}
.circleLegend {
color: deepskyblue;
width: 40px;
height: 40px;
font-size: 2.5em;
margin-top: -0.45em;
z-index: 12;
cursor: pointer;
}
.circleLegend img {
position: absolute;
right: 0.4em;
top: 1.4em;
display: none;
}
#closeCircleLegend {
position: absolute;
right: 0.5em;
top: 3.5em;
display: none;
font-size: 0.5em;
color: black;
cursor: pointer;
}
</style>
</head>
<body id="page-top">
<!-- Page Wrapper -->
<div id="wrapper">
<!-- Content Wrapper -->
<div id="content-wrapper" class="d-flex flex-column">
<!-- Main Content -->
<div id="content">
<!-- Begin Page Content -->
<div class="container-fluid">
<!-- Page Heading -->
<div class="header fixed-top d-sm-flex align-items-center justify-content-between mb-4 px-3">
<h1 class="h3 mb-0">Coronavirus<p><span>COVID-19</span> TRACKER</p>
</h1>
<h1 class="h5 mb-0">
<p>Global Situation:</p>
</h5>
<div class="h5 mb-0 g_confirmed header_stat">Confirmed 🌐<span>0</span></div>
<div class="h5 mb-0 g_recovered header_stat">Recovered 🌐<span>0</span></div>
<div class="h5 mb-0 g_deaths header_stat">Deaths 🌐<span>0</span></div>
<div class="h5 mb-0 g_mortality header_stat">Mortality(%) 🌐<span>0</span></div>
</div>
<div class="row mb-3" style="margin-top: 100px;">
<div class="col-xl-4">
<!-- select display country, default: NZ -->
<div class="dropdown">
<div class="form-group">
<select class="dropdown-country form-control"></select>
</div>
</div>
</div>
</div>
<div class="row">
<!-- Selected country detail in numbers -->
<div class="col-xl-2 col-lg-2 justify-content-center">
<div class="header d-sm-flex flex-column align-items-center justify-content-between">
<div class="h5 my-3 currentCountry header_stat"><span></span>Latest Situation</div>
<div class="h5 my-3 confirmed header_stat">Confirmed<span>0</span></div>
<div class="h5 my-3 recovered header_stat">Recovered<span>0</span></div>
<div class="h5 my-3 deaths header_stat">Deaths<span>0</span></div>
<div class="h5 my-3 morality header_stat">Mortality(%)<span>0</span></div>
</div>
</div>
<!-- World map -->
<div class="col-xl-10 col-lg-10">
<div class="card shadow mb-4">
<!-- Card Header -->
<div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
<h6 class="m-0 font-weight-bold text-primary">World Map</h6>
<span
style="position: absolute;font-weight: 700;font-size: 12px;color: #111;top:18px;right: 240px;">Mortality
Rate:</span>
<span class="colorplate"></span> <span
style="position: absolute;font-weight: 700;font-size: 10px;color: #111;top:4px;right: 120px;">Low
<‐ Medium ‐> High</span>
<span
style="position: absolute;font-weight: 700;font-size: 10px;color: #111;top:34px;right: 120px;">0% <‐ 10%
‐> 20%</span>
<div class="circleLegend">
<span
style="position: absolute;font-weight: 700;font-size: 12px;color: #111;top:18px;right: 65px;">Circle:</span>
<!-- Circle Legend Icon-->
<i class="fas fa-bullseye" onclick="openCircleLegend()"></i>
<div>
<img id="circleLegend" src="img/legend.png" />
<i id="closeCircleLegend" class="fas fa-times" onclick="closeCircleLegend()"></i>
</div>
</div>
</div>
<!-- Card Body Map -->
<div class="card-body">
<div class="chart-area">
<div id="map"></div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<!-- Daily New Cases bar Chart -->
<div class="col-xl-6 col-lg-7">
<div class="card shadow mb-4">
<!-- Card Header -->
<div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
<h6 class="m-0 font-weight-bold text-primary currentCountry"><span></span> Daily New Cases</h6>
</div>
<!-- Card Body -->
<div class="card-body">
<div class="chart-area">
<div id="chart_new_cases"></div>
</div>
</div>
</div>
</div>
<!-- Cumulative Cases line graph -->
<div class="col-xl-6 col-lg-7">
<div class="card shadow mb-4">
<!-- Card Header -->
<div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
<h6 class="m-0 font-weight-bold text-primary currentCountry"><span></span> Cumulative Cases</h6>
</div>
<!-- Card Body -->
<div class="card-body">
<div class="chart-area">
<div id="chart_cumulative_cases"></div>
</div>
</div>
</div>
</div>
<!-- Global Situation bar chart -->
<div class="col-xl-12 col-lg-7">
<div class="card shadow mb-4">
<!-- Card Header -->
<div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
<h6 class="m-0 font-weight-bold text-primary">Global Situation (Daily)</h6>
</div>
<!-- Card Body -->
<div class="card-body">
<div class="chart-area">
<div id="chart_moving_new_cases"></div>
</div>
</div>
</div>
</div>
</div>
<!-- Global Situation Table -->
<div class="row">
<div class="col-xl-12">
<div class="card shadow mb-4">
<div class="card-header py-3">
<h6 class="m-0 font-weight-bold text-primary">Situation by Country, Territory & Area</h6>
</div>
<div class="card-body" style="padding: 0;">
<div class="table-responsive">
<table class="table tableFixHead table-bordered" id="dataTable" width="100%" cellspacing="0">
<thead>
<th>Country/Region ⇅</th>
<th>Confirmed ⇅</th>
<th>Cumulative Total</th>
<th>Recovered ⇅</th>
<th>Deaths ⇅</th>
<th>Ratio (hover to see)</th>
</thead>
<tbody class="dataTable"></tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<!-- Page header -->
<div class="header d-sm-flex align-items-center justify-content-between mb-4">
<p class="mb-0 p-2" style="font-size: 14px;">This web-app relies upon publicly available data from multiple
sources. I hereby disclaimed any and all representation and warranties with respect to this web-app.
Cheers!</p>
</h1>
<div class="mb-0" style="text-align: right;"><img src="footer.png" width="80%" /></div>
</div>
</div>
<!-- /.container-fluid -->
</div>
<!-- End of Main Content -->
<!-- Footer -->
<footer class="sticky-footer bg-white">
<div class="container my-auto">
<div class="copyright text-center my-auto">
<span>Copyright © SuperUXR 2020</span>
</div>
</div>
</footer>
<!-- End of Footer -->
</div>
<!-- End of Content Wrapper -->
</div>
<!-- End of Page Wrapper -->
<!-- Scroll to Top Button-->
<a class="scroll-to-top rounded" href="#page-top">
<i class="fas fa-angle-up"></i>
</a>
<div class="d3-tooltip">a simple tooltip</div>
<!-- Bootstrap core JavaScript-->
<script src="js/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js" type="text/javascript"></script>
<script src="https://cdn.datatables.net/1.10.22/js/dataTables.bootstrap4.min.js" type="text/javascript"></script>
<script src="js/sb-admin-2.min.js"></script>
<script src="https://api.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.js"></script>
<script src="https://d3js.org/d3.v5.min.js"></script>
<script>
let maxDate = '2020-09-27'; //last date of the dataset
let data = [], sortData = [], labels = [];
let tooltip = $('.d3-tooltip');
let currentCountry = 'New Zealand'; //default selected country
let dates = [], deaths = [], recovered = [], totalCases = [];
let globalDeath = 0, globalRecovered = 0, globalTotalCases = 0, tglobalConf = 0;
let maxConfCase = 0;
let tglobalCumCases = [], globalCumCases = [];
let newCases = [], cumData = [], newCasesBar = [];
mapboxgl.accessToken = 'pk.eyJ1IjoianF1ZXJ5NDA0IiwiYSI6ImNpbDQwNHV0YjNzazB1eWtzYWRleXVmOGIifQ.HrzVBbMbMz7Zbxuoie03BQ';
let map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v11',
center: [13.180161, 32.885353],
zoom: 1
});
$(function () { $('[data-toggle="tooltip"]').tooltip(); }) //display the tooltips when the mouse is hovering
//open the circle legend
function openCircleLegend() {
document.getElementById("circleLegend").style.display = "block"
document.getElementById("closeCircleLegend").style.display = "block"
}
//close the circle legend
function closeCircleLegend() {
document.getElementById("circleLegend").style.display = "none"
document.getElementById("closeCircleLegend").style.display = "none"
}
let svg_height = 330; //svg height
let svgCum = d3.select("#chart_cumulative_cases").append("svg").attr("width", '100%').attr("height", svg_height);
let svgNewCases = d3.select("#chart_new_cases").append("svg").attr("width", '100%').attr("height", svg_height);
let svgMovingNewCases = d3.select("#chart_moving_new_cases").append("svg").attr("width", '100%').attr("height", svg_height);
//loading data
d3.csv("time-series-19-covid-combined.csv").then(function (data) {
let confirmData = [];
let container = map.getCanvasContainer();
let map_data = [];
let countryData = [];
for (var i = 0; i < data.length; i++) {
//get global cumulative cases
if (globalCumCases[data[i].Date]) {
globalCumCases[data[i].Date] = {
date: data[i].Date,
value: globalCumCases[data[i].Date].value + parseInt(data[i].Confirmed)
};
} else {
globalCumCases[data[i].Date] = {
date: data[i].Date,
value: parseInt(data[i].Confirmed)
};
}
//get global recovered number
if (data[i].Date == maxDate) {
if (parseInt(data[i].Recovered)) globalRecovered += parseInt(data[i].Recovered);
globalDeath += parseInt(data[i].Deaths);
globalTotalCases += parseInt(data[i].Confirmed);
//get details for every country (merge all the province to one country)
if (countryData[data[i]['Country/Region']]) {
countryData[data[i]['Country/Region']] = {
recovered: countryData[data[i]['Country/Region']].recovered + parseInt(data[i].Recovered),
death: countryData[data[i]['Country/Region']].death + parseInt(data[i].Deaths),
confirmed: countryData[data[i]['Country/Region']].confirmed + parseInt(data[i].Confirmed),
lat: data[i].Lat,
lng: data[i].Long
};
} else {
countryData[data[i]['Country/Region']] = {
recovered: parseInt(data[i].Recovered),
death: parseInt(data[i].Deaths),
confirmed: parseInt(data[i].Confirmed),
lat: data[i].Lat,
lng: data[i].Long
};
}
if (maxConfCase < countryData[data[i]['Country/Region']].confirmed)
maxConfCase = countryData[data[i]['Country/Region']].confirmed;
//final data
sortData.push({
country: data[i]['Country/Region'],
state: data[i]['Province/State'],
confirmed: data[i].Confirmed,
deaths: data[i].Deaths,
recovered: data[i].Recovered,
long: data[i].Long,
lat: data[i].Lat
})
}
//current country is NZ, display all relevant data with NZ as default
if (data[i]['Country/Region'] == currentCountry) {
$('.currentCountry span').html(data[i]['Country/Region']);
$('.recovered span').html(numberWithCommas(parseInt(data[i].Recovered)));
$('.confirmed span').html(numberWithCommas(parseInt(data[i].Confirmed)));
$('.deaths span').html(numberWithCommas(parseInt(data[i].Deaths)));
$('.mortality span').html((parseInt(data[i].Deaths) / parseInt(data[i].Confirmed)).toFixed(2));
deaths.push(parseInt(data[i].Deaths));
recovered.push(parseInt(data[i].Recovered));
totalCases.push(parseInt(data[i].Confirmed));
dates.push(data[i].Date);
}
}
//display all global data
$('.g_recovered span').html(numberWithCommas(globalRecovered));
$('.g_confirmed span').html(numberWithCommas(globalTotalCases));
$('.g_deaths span').html(numberWithCommas(globalDeath));
$('.g_mortality span').html((parseInt(globalDeath) / parseInt(globalTotalCases)).toFixed(2));
for (const country in countryData) {
//handle missing value
countryData['Canada'].recovered = 0;
//calculate cumulative, mortality, recovery, new cases ratio
let recRatio = Math.floor((countryData[country].recovered / globalRecovered) * 100);
let deathRatio = Math.floor((countryData[country].death / globalDeath) * 100);
let confRatio = Math.floor((countryData[country].confirmed / globalTotalCases) * 100);
let totalRatio = recRatio + deathRatio + confRatio;
//dropdown country selection
if (currentCountry == country) $('.dropdown-country').append('<option selected value="' + country + '">' + country + '</option>');
else $('.dropdown-country').append('<option value="' + country + '">' + country + '</option>');
//recovered data in the table
$('.globalRecoveredTable').append(`<tr>
<td>${country}</td>
<td>${countryData[country].recovered}</td>
<td>
<div style="color: #111; font-size:10px;">${recRatio}%</div>
<div class="progress">
<div class="progress-bar" role="progressbar" aria-valuenow="70" aria-valuemin="0" aria-valuemax="100" style="width:${recRatio}%"></div>
</div>
</td>
</tr>`);
//comfirmed data in the table
$('.globalCasesTable').append(`<tr>
<td>${country}</td>
<td>${countryData[country].confirmed}</td>
<td>
<div style="color: #111; font-size:10px;">${deathRatio}%</div>
<div class="progress">
<div class="progress-bar" role="progressbar" aria-valuenow="70" aria-valuemin="0" aria-valuemax="100" style="width:${deathRatio}%"></div>
</div>
</td>
</tr>`);
//add progress bars in the global table: cummulative, mortality/recovery/new cases
$('.dataTable').append(`<tr>
<td>${country}</td>
<td>${numberWithCommas(countryData[country].confirmed)}</td>
<td style="width:10%">
<div class="progress"><div class="progress-bar" role="progressbar" style="width:${(countryData[country].confirmed / maxConfCase) * 100}%" aria-valuenow="${countryData[country].confirmed / maxConfCase}" aria-valuemin="0" aria-valuemax="100"></div></div>
</td>
<td>${numberWithCommas(countryData[country].recovered)}</td>
<td>${numberWithCommas(countryData[country].death)}</td>
<td style="width:15%">
<div class="progress">
<div class="progress-bar bg-danger" role="progressbar" data-toggle="tooltip" data-placement="right" title="Mortality ${deathRatio}%" style="width:${deathRatio}%" aria-valuenow="${deathRatio}" aria-valuemin="0" aria-valuemax="${totalRatio}"></div>
<div class="progress-bar bg-success" role="progressbar" data-toggle="tooltip" data-placement="right" title="Recovery ${recRatio}%" style="width:${recRatio}%" aria-valuenow="${recRatio}" aria-valuemin="0" aria-valuemax="${totalRatio}"></div>
<div class="progress-bar bg-warning" role="progressbar" data-toggle="tooltip" data-placement="right" title="Newcases ${confRatio}%" style="width:${confRatio}%" aria-valuenow="${confRatio}" aria-valuemin="0" aria-valuemax="${totalRatio}"></div>
</div>
</td>
</tr>`);
map_data.push([countryData[country].lng, countryData[country].lat, countryData[country].confirmed, country, countryData[country].death]);
}
$('#dataTable').DataTable({ paging: false, searching: false, "order": [[1, 'dsc']] });
//date, confirm, recovered, death data in 190 days
for (var i = 190; i > 0; i--) {
cumData.push({
date: dates[dates.length - i],
confirmed: totalCases[totalCases.length - i],
recovered: recovered[recovered.length - i],
deaths: deaths[deaths.length - i],
});
confirmData.push({
date: d3.timeParse("%Y-%m-%d")(dates[dates.length - i]),
data: totalCases[totalCases.length - i]
});
}
//new cases in each 190 days
for (var i = 0; i < 190; i++) {
newCases.push(Math.abs(totalCases[i + 1] - totalCases[i]));
newCasesBar.push({
date: dates[i],
value: Math.abs(totalCases[i + 1] - totalCases[i])
});
}
//each day in global cumulative
for (tdata in globalCumCases) {
tglobalCumCases.push({
date: globalCumCases[tdata].date,
value: globalCumCases[tdata].value
})
}
//radius in the map
var radius = d3.scaleSqrt().domain([0, 1e6]).range([0, 20]);
//circle's color in the map
var color = d3.scaleOrdinal().domain([0, 1e6]).range(["#D76156", "#D17E51", "#F0C277", "#FDD197", "#F0A477", "#F5D258", "#F7F15C"])
//map container
var map_svg = d3.select(container).append("svg")
.attr("width", "100%")
.attr("height", "500")
.style("position", "absolute")
.style("z-index", 2);
//circle style
var dots = map_svg.selectAll("circle").data(map_data).enter().append("circle")
.attr("class", "bubble")
.style("fill", function (d) { return color(d[2]) })
.attr("stroke", function (d) { return color(d[2]) })
.attr("r", function (d) { return radius(d[2]); })
.on("mouseover", function (d, i) {
tooltip.html(`${d[3]} <br/>Confirmed: ${numberWithCommas(d[2])}<br/>Death: ${numberWithCommas(d[4])}`).css("visibility", "visible");
d3.select(this).attr("fill", '#ff0');
})
.on("mousemove", function () {
tooltip.css({ "top": (event.pageY - 10) + "px", "left": (event.pageX + 10) + "px" });
})
.on("mouseout", function () {
tooltip.html(``).css("visibility", "hidden");
d3.select(this).attr("fill", '#ddd');
});
//re-position
function project(d) {
return map.project(new mapboxgl.LngLat(d[0], d[1]));
}
//render map with new position
function render() {
dots.attr("cx", function (d) { return project(d).x; })
.attr("cy", function (d) { return project(d).y; });
}
map.on("viewreset", render);
map.on("move", render);
map.on("moveend", render);
render();
//refresh data when selected a country
$('.dropdown-country').change(function () {
currentCountry = this.value;
//transfer to the new country's position on the map
flyMe(countryData[this.value].lat, countryData[this.value].lng);
deaths = [], recovered = [], totalCases = [], dates = [], newCases = [], newCasesBar = [];
//update deatils data for this specific country
for (var i = 0; i < data.length; i++) {
if (data[i]['Country/Region'] == currentCountry) {
$('.currentCountry span').html(data[i]['Country/Region']);
$('.recovered span').html(numberWithCommas(parseInt(data[i].Recovered)));
$('.confirmed span').html(numberWithCommas(parseInt(data[i].Confirmed)));
$('.deaths span').html(numberWithCommas(parseInt(data[i].Deaths)));
$('.mortality span').html((parseInt(data[i].Deaths) / parseInt(data[i].Confirmed)).toFixed(2));
deaths.push(parseInt(data[i].Deaths));
recovered.push(parseInt(data[i].Recovered));
totalCases.push(parseInt(data[i].Confirmed));
dates.push(data[i].Date);
}
}
//new cases in each 190 days
for (var i = 0; i < 190; i++) {
newCases.push(Math.abs(totalCases[i + 1] - totalCases[i]));
newCasesBar.push({
date: dates[i],
value: Math.abs(totalCases[i + 1] - totalCases[i])
});
}
cumData = [];
//date, confirm, recovered, death data in 190 days
for (var i = 190; i > 0; i--) {
cumData.push({
date: dates[dates.length - i],
confirmed: totalCases[totalCases.length - i],
recovered: recovered[recovered.length - i],
deaths: deaths[deaths.length - i],
});
}
d3.selectAll("#chart_new_cases svg> *").remove();
currentCountryDailyNewCasesChart(svgNewCases, newCasesBar);
d3.selectAll("#chart_cumulative_cases svg> *").remove();
cumulativeChart(cumData);
});
//render each chart/graph
currentCountryDailyNewCasesChart(svgNewCases, newCasesBar);
globalCurveChart(svgMovingNewCases, tglobalCumCases);
cumulativeChart(cumData);
});
function currentCountryDailyNewCasesChart(svg, data) {
let max_bar_height = 0;
for (const d in data) if (max_bar_height < data[d].value) max_bar_height = data[d].value;
const max_bar_width = 100;
const bar_color = "#111";
const top_offset = 10;
const bottom_offset = 30;
const svg_width = svg.node().getBoundingClientRect().width;
let bar_width = Math.round((svg_width + 60) / data.length);
if (bar_width > max_bar_width) bar_width = max_bar_width;
let spacing = 0.15 * bar_width;
let scale = d3.scaleLinear().domain([0, max_bar_height]).range([0, svg_height]);
let scale_y_axis = d3.scaleLinear().domain([max_bar_height, 0]).range([0, svg_height]);
// Daily New Cases bar chart rect for the selection country
svg.selectAll("g").data(data).enter().append("rect")
.attr("fill", bar_color)
.attr("x", (d, i) => 30 + bar_width * i)
.attr("y", d => svg_height - scale(d.value))
.attr("width", bar_width - spacing)
.attr("height", d => scale(d.value))
.on("mouseover", function (d, i) {
tooltip.html(`${dateFormating(d.date)} New Cases: ${numberWithCommas(d.value)}`).css("visibility", "visible");
d3.select(this).attr("fill", '#ff0');
})
.on("mousemove", function () {
tooltip.css({ "top": (event.pageY - 10) + "px", "left": (event.pageX + 10) + "px" });
})
.on("mouseout", function () {
tooltip.html(``).css("visibility", "hidden");
d3.select(this).attr("fill", bar_color);
});
// x-axis
svg.append("line")
.attr("stroke", "#000000")
.attr("stroke-width", 2)
.attr("x1", 0)
.attr("y1", svg_height)
.attr("x2", bar_width * data.length)
.attr("y2", svg_height);
// y-axis
svg.append("g")
.attr("transform", "translate(0," + top_offset + ")")
.call(d3.axisRight(scale_y_axis));
}
function globalCurveChart(svg, data) {
let max_bar_height = 0;
for (const d in data) if (max_bar_height < data[d].value) max_bar_height = data[d].value;
const max_bar_width = 100;
const bar_color = "#111";
const top_offset = 10;
const bottom_offset = 30;
const svg_width = svg.node().getBoundingClientRect().width;
let bar_width = Math.round((svg_width) / data.length);
if (bar_width > max_bar_width) bar_width = max_bar_width;
let spacing = 0.15 * bar_width;
let scale = d3.scaleLinear().domain([0, max_bar_height]).range([0, svg_height]);
let scale_y_axis = d3.scaleLinear().domain([max_bar_height, 0]).range([0, svg_height]);
// curve for both cumulative cases and global situation(Daily)
var dt = d3.timeParse("%Y-%m-%d");
var x = d3.scaleLinear().domain([0, max_bar_height]).range([0, svg_width - 100]);
var y = d3.scaleLinear().domain([0, max_bar_height]).range([svg_height, 0]);
var prevPrevVal = 0;
var prevVal = 0;
var curVal = 0
var _movingSum;
var movingAverageLine = d3.line()
.x(function (d, i) { return x(d.value); })
.y(function (d, i) {
if (i == 0) {
prevPrevVal = scale_y_axis(d.value);
prevVal = scale_y_axis(d.value);
curVal = scale_y_axis(d.value);
} else if (i == 1) {
prevPrevVal = prevVal;
prevVal = curVal;
curVal = (prevVal + scale_y_axis(d.value)) / 2.0;
} else {
prevPrevVal = prevVal;
prevVal = curVal;
curVal = (prevPrevVal + prevVal + scale_y_axis(d.value)) / 3.0;
}
return curVal;
})
.curve(d3.curveNatural);
// Global Situation(Daily) bar rect
//input: sorted data
//output: rect bar chart
svg.selectAll("g").data(data).enter().append("rect")
.attr("fill", bar_color)
.attr("x", (d, i) => 0 + bar_width * i)
.attr("y", d => svg_height - scale(d.value))
.attr("width", bar_width - spacing)
.attr("height", d => scale(d.value))
.on("mouseover", function (d, i) {
tooltip.html(`${dateFormating(d.date)} Total Cases: ${numberWithCommas(d.value)}`).css("visibility", "visible");
d3.select(this).attr("fill", '#ff0');
})
.on("mousemove", function () {
tooltip.css({ "top": (event.pageY - 10) + "px", "left": (event.pageX + 10) + "px" });
})
.on("mouseout", function () {
tooltip.html(``).css("visibility", "hidden");
d3.select(this).attr("fill", bar_color);
});
// x-axis
svg.append("line")
.attr("stroke", "#000000")
.attr("stroke-width", 2)
.attr("x1", 0)
.attr("y1", svg_height)
.attr("x2", bar_width * data.length)
.attr("y2", svg_height);
// y-axis
svg.append("g")
.attr("transform", "translate(0," + top_offset + ")")
.call(d3.axisRight(scale_y_axis));
// moving avg
svg.append("path")
.attr("class", "average")
.attr("d", movingAverageLine(data));
}
//chart for the cumulative of a selected country
//input: data => sorted data
function cumulativeChart(data) {
var parseTime = d3.timeParse("%Y-%m-%d"),
formatDate = d3.timeFormat("%Y-%m-%d"),
bisectDate = d3.bisector(d => d.date).left,
formatValue = d3.format(",.0f");
data.forEach(function (d) { d.date = parseTime(d.date); return d; })
var margin = { top: 15, right: 35, bottom: 15, left: 35 },
width = svgCum.node().getBoundingClientRect().width,
height = 300;
var x = d3.scaleTime().rangeRound([margin.left, width - margin.right]).domain(d3.extent(data, d => d.date))
var y = d3.scaleLinear().rangeRound([height - margin.bottom, margin.top]);
var z = d3.scaleOrdinal(d3.schemeSet1);
var line = d3.line().curve(d3.curveCardinal).x(d => x(d.date)).y(d => y(d.degrees));
svgCum.append("g")
.attr("class", "x-axis")
.attr("transform", "translate(0," + (height - margin.bottom) + ")")
.call(d3.axisBottom(x).tickFormat(d3.timeFormat("%b")));
svgCum.append("g")
.attr("class", "y-axis")
.attr("transform", "translate(" + margin.left + ",0)");
var focus = svgCum.append("g").attr("class", "focus").style("display", "none");
focus.append("line").attr("class", "lineHover")
.style("stroke", "#999")
.attr("stroke-width", 1)
.style("shape-rendering", "crispEdges")
.style("opacity", 0.5)
.attr("y1", -height)
.attr("y2", 0);
focus.append("text").attr("class", "lineHoverDate").attr("text-anchor", "middle").attr("font-size", 12);
var overlay = svgCum.append("rect")
.attr("class", "overlay")
.attr("x", margin.left)
.attr("width", width - margin.right - margin.left)
.attr("height", height)
update(1, 0);
function update(input, speed) {
var copy = ["confirmed", "recovered", "deaths"];
var cities = copy.map(function (id) {
return {
id: id,
values: data.map(d => { return { date: d.date, degrees: +d[id] } })
};
});
y.domain([
d3.min(cities, d => d3.min(d.values, c => c.degrees)),
d3.max(cities, d => d3.max(d.values, c => c.degrees))
]).nice();
svgCum.selectAll(".y-axis").transition().duration(speed).call(d3.axisLeft(y).tickSize(-width + margin.right + margin.left))
var city = svgCum.selectAll(".cities").data(cities);
city.exit().remove();
city.enter().insert("g", ".focus").append("path")
.attr("class", "line cities")
.style("stroke", d => z(d.id))
.merge(city)
.transition().duration(speed)
.attr("d", d => line(d.values))
tooltip(copy);
}
//create tooltips
function tooltip(copy) {
//create tooltips for the cummulative cases
var labels = focus.selectAll(".lineHoverText").data(copy)
labels.enter().append("text")
.attr("class", "lineHoverText")
.style("fill", d => z(d))
.attr("text-anchor", "start")
.attr("font-size", 12)
.attr("dy", (_, i) => 1 + i * 2 + "em")
.merge(labels);
//create tooltips for the map
var circles = focus.selectAll(".hoverCircle").data(copy)
circles.enter().append("circle")
.attr("class", "hoverCircle")
.style("fill", d => z(d))
.attr("r", 2.5)
.merge(circles);
svgCum.selectAll(".overlay")
.on("mouseover", function () { focus.style("display", null); })
.on("mouseout", function () { focus.style("display", "none"); })
.on("mousemove", mousemove);
function mousemove() {
var x0 = x.invert(d3.mouse(this)[0]),
i = bisectDate(data, x0, 1),
d0 = data[i - 1],
d1 = data[i],
d = x0 - d0.date > d1.date - x0 ? d1 : d0;
focus.select(".lineHover").attr("transform", "translate(" + x(d.date) + "," + height + ")");
focus.select(".lineHoverDate").attr("transform", "translate(" + x(d.date) + "," + (height + margin.bottom) + ")")
.text(formatDate(d.date));
focus.selectAll(".hoverCircle")
.attr("cy", e => y(d[e]))
.attr("cx", x(d.date));
focus.selectAll(".lineHoverText")
.attr("transform",
"translate(" + (x(d.date)) + "," + height / 2.5 + ")")
.text(e => e + " " + formatValue(d[e]));
x(d.date) > (width - width / 4)
? focus.selectAll("text.lineHoverText")
.attr("text-anchor", "end")
.attr("dx", -10)
: focus.selectAll("text.lineHoverText")
.attr("text-anchor", "start")
.attr("dx", 10)
}
}
}
//transer on the map
function flyMe(lat, lng) {
map.flyTo({
center: [
lng,
lat
],
essential: true
});
}
//format the data
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
//format the date
function dateFormating(d) {
var parseTime = d3.timeParse("%Y-%m-%d");
var formatTime = d3.timeFormat("%b %d");
return formatTime(parseTime(d));
}
</script>
</body>
</html>