-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
901 lines (795 loc) · 42.6 KB
/
index.html
File metadata and controls
901 lines (795 loc) · 42.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>California Infectious Disease Dashboard</title> <script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"
integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY="
crossorigin=""/>
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"
integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo="
crossorigin=""></script>
<style>
body {
font-family: 'Inter', sans-serif; /* Using Inter font as a Tailwind default */
background-color: #f3f4f6; /* Light gray background */
}
.filter-select {
min-width: 150px;
}
.summary-card {
background-color: white;
border-radius: 0.5rem; /* rounded-lg */
padding: 1.5rem; /* p-6 */
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06); /* shadow-md */
}
.chart-container {
position: relative;
height: 400px; /* Consistent height for charts */
width: 100%; /* Ensure chart container takes full width of its parent */
}
/* Ensure canvas elements take up the full space of their container */
.chart-container canvas {
display: block;
width: 100%;
height: 100%;
}
#map-container { /* Ensure map container has a defined height */
height: 400px;
width: 100%;
border-radius: 0.5rem; /* Consistent rounding */
}
@media (max-width: 768px) { /* Mobile responsiveness */
.filters-grid {
grid-template-columns: repeat(2, minmax(0, 1fr)); /* 2 columns on mobile */
}
.summary-grid {
grid-template-columns: repeat(1, minmax(0, 1fr)); /* 1 column on mobile */
}
.chart-container {
height: 300px; /* Adjust chart height for smaller screens */
}
#map-container {
height: 300px; /* Adjust map height for smaller screens */
}
}
</style>
</head>
<body class="bg-gray-100 p-4 md:p-8">
<div class="container mx-auto">
<header class="mb-8 text-center">
<h1 class="text-3xl md:text-4xl font-bold text-gray-800">California Infectious Disease Dashboard</h1>
<p class="text-gray-600">Data from 2001-2023 (Provisional)</p>
</header>
<section id="filters" class="mb-8 p-6 bg-white rounded-lg shadow-lg">
<h2 class="text-xl font-semibold text-gray-700 mb-4">Filters</h2>
<div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4 items-end filters-grid">
<div>
<label for="disease-filter" class="block text-sm font-medium text-gray-700">Disease</label>
<select id="disease-filter" class="mt-1 block w-full p-2 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 filter-select">
<option value="">All Diseases</option>
</select>
</div>
<div>
<label for="county-filter" class="block text-sm font-medium text-gray-700">County</label>
<select id="county-filter" class="mt-1 block w-full p-2 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 filter-select">
<option value="">All Counties</option>
</select>
</div>
<div>
<label for="year-filter" class="block text-sm font-medium text-gray-700">Year</label>
<select id="year-filter" class="mt-1 block w-full p-2 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 filter-select">
<option value="">All Years</option>
</select>
</div>
<div>
<label for="sex-filter" class="block text-sm font-medium text-gray-700">Sex</label>
<select id="sex-filter" class="mt-1 block w-full p-2 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 filter-select">
<option value="">All</option>
</select>
</div>
<button id="clear-filters-btn" class="w-full bg-red-500 hover:bg-red-600 text-white font-semibold py-2 px-4 rounded-md shadow-sm transition duration-150 ease-in-out self-end">
Clear Filters
</button>
</div>
</section>
<section id="summary-stats" class="mb-8 grid grid-cols-1 md:grid-cols-3 gap-4 summary-grid">
<div class="summary-card text-center">
<h3 class="text-lg font-medium text-gray-500">Total Cases</h3>
<p id="total-cases" class="text-3xl font-bold text-indigo-600">0</p>
</div>
<div class="summary-card text-center">
<h3 class="text-lg font-medium text-gray-500">First Reported Year</h3>
<p id="first-reported" class="text-3xl font-bold text-indigo-600">N/A</p>
</div>
<div class="summary-card text-center">
<h3 class="text-lg font-medium text-gray-500">Last Reported Year</h3>
<p id="last-reported" class="text-3xl font-bold text-indigo-600">N/A</p>
</div>
</section>
<section class="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-8">
<div class="bg-white p-6 rounded-lg shadow-lg">
<h2 class="text-xl font-semibold text-gray-700 mb-4">Filtered Data Breakdown</h2>
<div class="chart-container">
<canvas id="barChart"></canvas>
</div>
</div>
<div class="bg-white p-6 rounded-lg shadow-lg">
<h2 class="text-xl font-semibold text-gray-700 mb-4">Cases by County Map</h2>
<div id="map-container" class="w-full border border-gray-200 rounded-md">
</div>
</div>
</section>
<section class="bg-white p-6 rounded-lg shadow-lg mt-8">
<h2 class="text-xl font-semibold text-gray-700 mb-4">Cases Over Time</h2>
<div class="chart-container">
<canvas id="lineChart"></canvas>
</div>
</section>
<footer class="mt-12 text-center text-sm text-gray-500">
<p>Data Source: `idb_2001-2023.json` (California Department of Public Health - Provisional).</p>
<p>Map Data: `california-counties.geojson`.</p>
<p>This dashboard is for informational purposes. Always consult official sources for health data.</p>
</footer>
</div>
<script>
// --- DATA LOADING ---
function csvToJSON(csv) {
const lines = csv.split("\n");
const headers = lines[0].split(",").map(h => h.trim());
return lines.slice(1).reduce((acc, line) => {
const data = line.split(",").map(d => d.trim());
if (data.length === headers.length) {
const obj = {};
headers.forEach((header, index) => obj[header] = data[index]);
acc.push(obj);
}
return acc;
}, []);
}
let masterData = [];
// --- AGGREGATE IDENTIFIERS (GLOBAL) ---
// These MUST match exactly how they appear in your CSV data.
const AGGREGATE_SEX_VALUE = "Total";
// COMMON ASSUMPTION: "California" is often used in 'County' columns for statewide totals.
// Adjust this if your data uses a different identifier (e.g., "Statewide", "All CA").
const AGGREGATE_COUNTY_IDENTIFIER = "California";
// These will be set after masterData is loaded
let hasAggregateSexIdentifier = false;
let hasStatewideAggregateCountyIdentifier = false;
// --- DOM ELEMENT REFERENCES ---
const diseaseFilter = document.getElementById('disease-filter');
const countyFilter = document.getElementById('county-filter');
const yearFilter = document.getElementById('year-filter');
const sexFilter = document.getElementById('sex-filter');
const clearFiltersBtn = document.getElementById('clear-filters-btn');
const totalCasesEl = document.getElementById('total-cases');
const firstReportedEl = document.getElementById('first-reported');
const lastReportedEl = document.getElementById('last-reported');
const barChartCanvas = document.getElementById('barChart');
let barChartInstance = null;
const lineChartCanvas = document.getElementById('lineChart');
let lineChartInstance = null;
// --- MAP VARIABLES ---
let map = null;
let geojsonLayer = null;
let californiaGeoJsonData = null;
// --- STATE VARIABLES ---
let isApplyingFilters = false;
// --- INITIALIZE DASHBOARD ---
async function initializeDashboard() {
try {
// Attempt to fetch the primary dataset
const response = await fetch('idb_2001-2023.csv');
if (!response.ok) {
throw new Error(`Failed to fetch disease data: ${response.status} ${response.statusText}`);
}
const csvData = await response.text();
masterData = csvToJSON(csvData);
// After masterData is loaded, determine if aggregate identifiers exist
if (masterData.length > 0) {
hasAggregateSexIdentifier = masterData.some(d => d.Sex === AGGREGATE_SEX_VALUE);
hasStatewideAggregateCountyIdentifier = masterData.some(d => d.County === AGGREGATE_COUNTY_IDENTIFIER);
}
if (!response.ok) {
throw new Error(`Failed to fetch disease data: ${response.status} ${response.statusText}. Check file path and ensure it's hosted.`);
}
// Ensure masterData is an array. If not, treat as empty to prevent further errors.
if (!Array.isArray(masterData)) {
console.warn("Fetched disease data ('idb_2001-2023.json') is not an array. Dashboard will initialize with empty data.", masterData);
masterData = []; // This will lead to "No data available" messages, which is correct.
} else if (masterData.length === 0) {
console.warn("Disease data file ('idb_2001-2023.json') is empty. Charts will show 'No data available'.");
}
// Populate filter dropdowns based on available masterData
populateFilters();
// Initialize the map (fetches GeoJSON internally)
await initializeMap();
// Apply initial filters (which means showing all data if masterData is populated)
// Ensure canvas elements exist before trying to draw on them.
if (barChartCanvas && lineChartCanvas) {
applyFilters();
} else {
console.error("Chart canvas elements not found in the DOM. Cannot apply initial filters or display charts.");
// Display error on summary cards as well if canvases are missing
totalCasesEl.textContent = 'Error';
firstReportedEl.textContent = 'Error';
lastReportedEl.textContent = 'Error';
}
// Add event listeners for filter changes
addEventListeners();
} catch (error) {
console.error("Error initializing dashboard:", error);
// Display errors on summary cards
totalCasesEl.textContent = 'Error';
firstReportedEl.textContent = 'Error';
lastReportedEl.textContent = 'Error';
// Display errors on chart canvases
displayChartError(barChartCanvas, `Chart Error: ${error.message}`);
displayChartError(lineChartCanvas, `Chart Error: ${error.message}`);
const mapContainer = document.getElementById('map-container');
if(mapContainer) mapContainer.innerHTML = `<p class="text-center text-red-500 p-4">Error loading dashboard: ${error.message}</p>`;
}
}
// --- POPULATE FILTER DROPDOWNS ---
function populateFilters() {
// Clear existing options but keep the default "All"
diseaseFilter.innerHTML = '<option value="">All Diseases</option>';
yearFilter.innerHTML = '<option value="">All Years</option>';
sexFilter.innerHTML = '<option value="">All</option>';
// County filter is populated after GeoJSON loads in initializeMap
if (masterData.length === 0) return; // Don't try to populate from empty data
// Extract unique, sorted values for filters. Filter out any null/undefined values.
const diseases = [...new Set(masterData.map(item => item.Disease))].filter(Boolean).sort();
const years = [...new Set(masterData.map(item => parseInt(item.Year)))].filter(y => !isNaN(y)).sort((a,b) => b-a); // Numeric sort, descending
const sexes = [...new Set(masterData.map(item => item.Sex))].filter(Boolean).sort();
diseases.forEach(d => {
const option = document.createElement('option');
option.value = d;
option.textContent = d;
diseaseFilter.appendChild(option);
});
years.forEach(y => {
const option = document.createElement('option');
option.value = y; // Value is the number
option.textContent = y; // Text is the number
yearFilter.appendChild(option);
});
sexes.forEach(s => {
const option = document.createElement('option');
option.value = s;
option.textContent = s;
sexFilter.appendChild(option);
});
}
// --- ADD EVENT LISTENERS ---
function addEventListeners() {
diseaseFilter.addEventListener('change', applyFilters);
countyFilter.addEventListener('change', applyFilters);
yearFilter.addEventListener('change', applyFilters);
sexFilter.addEventListener('change', applyFilters);
clearFiltersBtn.addEventListener('click', () => {
// Reset all filter dropdowns to their default "All" value
diseaseFilter.value = "";
countyFilter.value = "";
yearFilter.value = "";
sexFilter.value = "";
applyFilters(); // Re-apply filters to update the view
});
}
// --- APPLY FILTERS AND UPDATE DISPLAY ---
function applyFilters() {
// Guard against re-entrant calls to prevent stack overflow
if (isApplyingFilters) {
console.warn("applyFilters() called while already running. Aborting to prevent recursion.");
return;
}
isApplyingFilters = true;
try {
const selectedDisease = diseaseFilter.value;
const selectedCounty = countyFilter.value;
const selectedYearStr = yearFilter.value; // Year from filter is a string
const selectedSex = sexFilter.value;
// Filter masterData based on current selections
const filteredData = masterData.filter(item => {
// Ensure item.Year is treated as a number for comparison
const itemYear = parseInt(item.Year);
// 1. Disease Filter
const diseaseMatch = !selectedDisease || item.Disease === selectedDisease;
if (!diseaseMatch) return false;
// 2. Sex Filter
let sexMatch;
if (selectedSex) {
// A specific sex is selected (e.g., "Male", "Female", or "Total" if it's an option)
sexMatch = item.Sex === selectedSex;
} else {
// "All" sexes is selected (selectedSex is an empty string)
if (hasAggregateSexIdentifier) {
// If "All" sexes selected and an aggregate sex identifier (e.g., "Total") exists, use those rows.
sexMatch = item.Sex === AGGREGATE_SEX_VALUE;
} else {
// Otherwise (no aggregate sex identifier), "All" means sum all available individual sex records.
sexMatch = true;
}
}
if (!sexMatch) return false;
// 3. County Filter
let countyMatch;
if (selectedCounty) { // A specific county is selected from the dropdown
countyMatch = item.County === selectedCounty;
} else { // "All Counties" is selected (selectedCounty is an empty string)
if (hasStatewideAggregateCountyIdentifier) {
// If "All Counties" selected AND a statewide aggregate identifier exists, use those rows.
countyMatch = item.County === AGGREGATE_COUNTY_IDENTIFIER;
} else {
// Otherwise, "All Counties" means include all actual counties (for summing, if no statewide total row).
countyMatch = true;
}
}
if (!countyMatch) return false;
// 4. Year Filter (assuming 'Year' in data is numeric and "All Years" means sum across them)
const yearMatch = !selectedYearStr || itemYear === parseInt(selectedYearStr);
if (!yearMatch) return false;
return true; // All conditions met
});
// Update all dashboard components with the filtered data
updateSummaryStats(filteredData);
updateBarChart(filteredData);
updateLineChart(filteredData);
updateMapVisualization(selectedCounty); // Map visualization might only need selectedCounty
} catch (e) {
console.error("Error during applyFilters processing:", e);
// Optionally, display a user-facing error message here
} finally {
isApplyingFilters = false; // Reset the guard flag
}
}
// --- UPDATE SUMMARY STATISTICS ---
function updateSummaryStats(data) {
// Calculate total cases from the 'Cases' property of items in the data array
const totalCases = data.reduce((sum, item) => sum + (Number(item.Cases) || 0), 0);
let firstReportedYear = 'N/A';
let lastReportedYear = 'N/A';
if (data.length > 0) {
// Extract valid years, convert to numbers, and find min/max
const yearsInData = data.map(item => parseInt(item.Year)).filter(year => !isNaN(year));
if (yearsInData.length > 0) {
firstReportedYear = Math.min(...yearsInData).toString();
lastReportedYear = Math.max(...yearsInData).toString();
}
}
// Update the DOM elements with formatted values
totalCasesEl.textContent = totalCases.toLocaleString(); // Format number with commas
firstReportedEl.textContent = firstReportedYear;
lastReportedEl.textContent = lastReportedYear;
}
// --- UTILITY TO DISPLAY ERROR/NO DATA ON CHART CANVAS ---
function displayChartError(canvas, message) {
if (!canvas) {
console.error("displayChartError called with null canvas");
return;
}
// Ensure canvas drawing surface matches its styled size.
if (canvas.width !== canvas.clientWidth || canvas.height !== canvas.clientHeight) {
canvas.width = canvas.clientWidth;
canvas.height = canvas.clientHeight;
}
const ctx = canvas.getContext('2d');
if (canvas.width === 0 || canvas.height === 0) {
// console.warn(`Canvas ${canvas.id || 'Unnamed'} has zero dimensions. Cannot display message.`);
return; // Avoid drawing on a zero-size canvas
}
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.font = "14px 'Inter', sans-serif";
if (message && (message.toLowerCase().includes("error") || message.toLowerCase().includes("failed"))) {
ctx.fillStyle = "#ef4444"; // Red for errors
} else {
ctx.fillStyle = "#6b7280"; // Gray for "no data"
}
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
const maxWidth = canvas.width - 40;
const lineHeight = 18;
const words = (message || 'No data available.').split(' ');
let lines = [];
let currentLine = '';
for (let n = 0; n < words.length; n++) {
const testLine = currentLine + words[n] + ' ';
const metrics = ctx.measureText(testLine);
const testWidth = metrics.width;
if (testWidth > maxWidth && currentLine.length > 0) {
lines.push(currentLine.trim());
currentLine = words[n] + ' ';
} else {
currentLine = testLine;
}
}
lines.push(currentLine.trim());
lines = lines.filter(line => line.length > 0);
if (lines.length === 0) lines.push('No data available.');
const totalTextHeight = lines.length * lineHeight;
let startY = (canvas.height - totalTextHeight) / 2 + (lineHeight / 2);
for (let i = 0; i < lines.length; i++) {
ctx.fillText(lines[i], canvas.width / 2, startY + (i * lineHeight));
}
}
// --- BAR CHART FOR FILTERED DATA ---
function updateBarChart(data) {
// Destroy existing chart instance if it exists
if (barChartInstance) {
barChartInstance.destroy();
barChartInstance = null;
}
if (!barChartCanvas) {
console.error("Bar chart canvas ('barChart') not found!");
return;
}
const selectedDisease = diseaseFilter.value;
const selectedCounty = countyFilter.value;
const selectedYearStr = yearFilter.value;
// Handle cases where data is empty
if (data.length === 0 && masterData.length > 0) {
displayChartError(barChartCanvas, 'No data for chart with current filters.');
return;
}
if (masterData.length === 0 && data.length === 0){
displayChartError(barChartCanvas, 'No data available to display.');
return;
}
// Aggregate data for the chart
const casesByCategory = {};
// Group by County if a Year is selected, otherwise group by Year
const groupByKey = selectedYearStr ? 'County' : 'Year';
data.forEach(item => {
const categoryValue = item[groupByKey];
if (!categoryValue) return; // Skip if category key is missing
if (!casesByCategory[categoryValue]) casesByCategory[categoryValue] = 0;
casesByCategory[categoryValue] += (Number(item.Cases) || 0);
});
// Sort categories (numerically for years, alphabetically for counties)
const categories = Object.keys(casesByCategory).sort((a, b) => {
return groupByKey === 'Year' ? parseInt(a) - parseInt(b) : a.localeCompare(b);
});
// If no categories could be formed from the data
if (categories.length === 0 && data.length > 0) {
displayChartError(barChartCanvas, 'Could not generate chart categories from data.');
return;
}
if (categories.length === 0) {
displayChartError(barChartCanvas, 'No categories to display for the chart.');
return;
}
// Prepare chart data and options
const chartData = {
labels: categories,
datasets: [{
label: 'Cases',
data: categories.map(category => casesByCategory[category]),
backgroundColor: 'rgba(59, 130, 246, 0.7)',
borderColor: 'rgba(59, 130, 246, 1)',
borderWidth: 1,
borderRadius: 5,
}]
};
const chartOptions = {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: { display: true, position: 'top' },
title: {
display: true,
text: `Cases ${selectedDisease ? 'for ' + selectedDisease : ''} ${selectedCounty ? 'in ' + selectedCounty : ''} ${selectedYearStr ? 'for ' + selectedYearStr : ''}`.trim() || 'Overall Cases Breakdown'
},
tooltip: {
callbacks: {
label: function(context) {
return `${context.dataset.label}: ${context.parsed.y.toLocaleString()}`;
}
}
}
},
scales: {
x: { title: { display: true, text: groupByKey } },
y: { title: { display: true, text: 'Number of Cases' }, beginAtZero: true, ticks: { callback: value => value.toLocaleString() } }
}
};
// Create the new chart
barChartInstance = new Chart(barChartCanvas, {
type: 'bar',
data: chartData,
options: chartOptions
});
}
// --- MAP VISUALIZATION ---
const BASE_COUNTY_STYLE = {
color: "#4A5568",
weight: 1,
opacity: 0.9,
fillOpacity: 0.65
};
const HIGHLIGHTED_COUNTY_STYLE = {
...BASE_COUNTY_STYLE,
fillColor: "#3B82F6",
fillOpacity: 0.85,
weight: 2.5,
color: "#1D4ED8",
};
// Generates a color from a string for consistent county coloring
function stringToColor(str) {
let hash = 0;
for (let i = 0; i < str.length; i++) {
hash = str.charCodeAt(i) + ((hash << 5) - hash);
hash = hash & hash; // Convert to 32bit integer
}
let r = (hash & 0xFF0000) >> 16;
let g = (hash & 0x00FF00) >> 8;
let b = hash & 0x0000FF;
// Adjust components to ensure reasonable brightness and color variety
r = 30 + (r % 195);
g = 30 + (g % 195);
b = 30 + (b % 195);
// Avoid shades too close to the highlight color (blue)
if (Math.abs(r - 59) < 30 && Math.abs(g - 130) < 30 && Math.abs(b - 246) < 30) {
g = (g + 100) % 195 + 30;
}
return "#" + ("000000" + ((r << 16) | (g << 8) | b).toString(16)).slice(-6);
}
async function initializeMap() {
const mapContainer = document.getElementById('map-container');
if (!mapContainer) {
console.error("Map container not found!");
return;
}
mapContainer.innerHTML = ''; // Clear previous content (e.g., error messages)
const californiaBounds = [[32.5, -124.5], [42, -114.0]]; // Approx. CA bounds
// Remove existing map instance if one exists (e.g., during a hot reload scenario)
if (map) {
map.remove();
map = null;
}
map = L.map('map-container', {
center: [37.0, -119.5], zoom: 6, maxBounds: californiaBounds, minZoom: 5
});
// Add base tile layer (OpenStreetMap)
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
maxZoom: 18
}).addTo(map);
try {
// Fetch GeoJSON data for California counties
const response = await fetch('california-counties.geojson');
if (!response.ok) {
throw new Error(`Failed to fetch GeoJSON: ${response.status} ${response.statusText}. Check file path and ensure it's hosted.`);
}
californiaGeoJsonData = await response.json();
// Validate GeoJSON data
if (!californiaGeoJsonData || !californiaGeoJsonData.features || californiaGeoJsonData.features.length === 0) {
console.warn("GeoJSON data is empty or invalid.");
if(mapContainer) mapContainer.innerHTML = `<p class="text-center text-yellow-500 p-4">Map data (GeoJSON) is empty or invalid. Counties cannot be displayed.</p>`;
return;
}
// Populate County Filter Dropdown from GeoJSON properties
if (countyFilter && californiaGeoJsonData && californiaGeoJsonData.features) {
countyFilter.innerHTML = '<option value="">All Counties</option>';
const countyNamesForDropdown = [];
const countySet = new Set();
californiaGeoJsonData.features.forEach(feature => {
// Ensure 'feature.properties.name' matches 'County' field in idb_2001-2023.json
const countyValue = feature.properties.name;
const countyDisplayText = feature.properties.NAME || feature.properties.name; // Use NAME if available, fallback to name
if (countyValue && !countySet.has(countyValue)) {
countySet.add(countyValue);
countyNamesForDropdown.push({ value: countyValue, text: countyDisplayText });
}
});
countyNamesForDropdown.sort((a, b) => a.text.localeCompare(b.text));
countyNamesForDropdown.forEach(county => {
const option = document.createElement('option');
option.value = county.value;
option.textContent = county.text;
countyFilter.appendChild(option);
});
}
// Remove old GeoJSON layer if it exists
if (geojsonLayer) {
map.removeLayer(geojsonLayer);
geojsonLayer = null;
}
// Create and add the new GeoJSON layer
geojsonLayer = L.geoJson(californiaGeoJsonData, {
style: function(feature) {
const countyId = feature.properties.name || 'UnknownCounty';
// Store or generate a default color for each county
if (!feature.properties.defaultColor) {
feature.properties.defaultColor = stringToColor(countyId + "salt"); // Add salt for color variation
}
return { ...BASE_COUNTY_STYLE, fillColor: feature.properties.defaultColor };
},
onEachFeature: function(feature, layer) {
const countyDisplayName = feature.properties.NAME || feature.properties.name || "N/A";
// This 'name' property MUST match county names in your disease data for filtering and tooltips.
const countyValueForFiltering = feature.properties.name;
// Bind a tooltip to each county layer
layer.bindTooltip(() => {
const selectedDisease = diseaseFilter.value;
let tooltipContent = `<b>${countyDisplayName}</b>`;
if (masterData.length > 0 && countyValueForFiltering) {
const currentSelectedYearStr = yearFilter.value;
const currentSelectedSex = sexFilter.value; // Sex selected in the main filter
// Start with data for the specific county of this map feature
let countySpecificData = masterData.filter(item => item.County === countyValueForFiltering);
// Apply year filter from main controls
if (currentSelectedYearStr) {
countySpecificData = countySpecificData.filter(item => parseInt(item.Year) === parseInt(currentSelectedYearStr));
}
// Apply sex filter logic, mirroring applyFilters and using global aggregate flags
let sexFilteredDataForTooltip;
if (currentSelectedSex) { // A specific sex is selected in the main filter
sexFilteredDataForTooltip = countySpecificData.filter(item => item.Sex === currentSelectedSex);
} else { // "All" sexes selected in the main filter
if (hasAggregateSexIdentifier) { // Use global flag
// Filter this county's data for the aggregate sex value (e.g., "Total")
sexFilteredDataForTooltip = countySpecificData.filter(item => item.Sex === AGGREGATE_SEX_VALUE);
} else {
// No global aggregate sex, so "All" means sum all available sex records for this county
sexFilteredDataForTooltip = countySpecificData;
}
}
// Calculate total cases for this county with all active filters applied
const casesInCountyAllDiseases = sexFilteredDataForTooltip
.reduce((sum, item) => sum + (Number(item.Cases) || 0), 0);
tooltipContent += `<br>Total Cases (active filters): ${casesInCountyAllDiseases.toLocaleString()}`;
// If a specific disease is selected in the main filter, show its count too
if (selectedDisease) {
const casesForSelectedDisease = sexFilteredDataForTooltip // Start with already filtered data for year and sex
.filter(item => item.Disease === selectedDisease)
.reduce((sum, item) => sum + (Number(item.Cases) || 0), 0);
tooltipContent += `<br>${selectedDisease}: ${casesForSelectedDisease.toLocaleString()}`;
}
} else if (!countyValueForFiltering) {
tooltipContent += "<br>County name missing in GeoJSON.";
} else if (masterData.length === 0) {
tooltipContent += "<br>Disease data not loaded."
}
return tooltipContent;
});
// Add click listener to county layers
layer.on('click', function(e) {
// When a county on the map is clicked, update the county filter dropdown
// and re-apply all filters to update the dashboard.
if (countyValueForFiltering) {
countyFilter.value = countyValueForFiltering;
applyFilters();
}
});
}
}).addTo(map);
} catch (error) {
console.error("Error loading or processing GeoJSON for map:", error);
if(mapContainer) mapContainer.innerHTML = `<p class="text-center text-red-500 p-4">Could not load map data: ${error.message}. Ensure 'california-counties.geojson' is present and valid. Check console.</p>`;
}
}
// Updates the map visualization based on the selected county
function updateMapVisualization(selectedCountyName) {
if (!geojsonLayer || !map) return; // Do nothing if map or layer isn't initialized
let highlightedLayer = null;
geojsonLayer.eachLayer(function(layer) {
const geoJsonCountyName = layer.feature.properties.name;
// If a county is selected and matches this layer, highlight it
if (geoJsonCountyName && selectedCountyName && geoJsonCountyName.toLowerCase() === selectedCountyName.toLowerCase()) {
layer.setStyle(HIGHLIGHTED_COUNTY_STYLE);
layer.bringToFront(); // Bring highlighted layer to the front
highlightedLayer = layer;
} else {
// Otherwise, revert to its default style
const defaultColor = layer.feature.properties.defaultColor || stringToColor((geoJsonCountyName || "unknown") + "salt");
layer.setStyle({ ...BASE_COUNTY_STYLE, fillColor: defaultColor });
}
});
// Zoom to the highlighted county or reset view
if (highlightedLayer) {
map.fitBounds(highlightedLayer.getBounds(), { paddingTopLeft: [20,20], paddingBottomRight: [20,20], maxZoom: 8 });
} else if (!selectedCountyName && californiaGeoJsonData && geojsonLayer.getLayers().length > 0) {
// If "All Counties" is selected, fit map to show all counties
if (geojsonLayer.getBounds().isValid()) {
map.fitBounds(geojsonLayer.getBounds());
} else {
map.setView([37.0, -119.5], 6); // Fallback reset
}
} else if (!selectedCountyName) { // Fallback if no county selected and no GeoJSON bounds
map.setView([37.0, -119.5], 6);
}
}
// --- LINE CHART FOR CASES OVER TIME ---
function updateLineChart(data) {
if (lineChartInstance) {
lineChartInstance.destroy();
lineChartInstance = null;
}
if (!lineChartCanvas) {
console.error("Line chart canvas ('lineChart') not found!");
return;
}
// Handle empty data scenarios
if (data.length === 0 && masterData.length > 0) {
displayChartError(lineChartCanvas, 'No data for line chart with current filters.');
return;
}
if (masterData.length === 0 && data.length === 0){
displayChartError(lineChartCanvas, 'No data available to display.');
return;
}
// Determine if data includes month-level granularity
const hasMonthData = data.length > 0 && data.some(item => typeof item.Month !== 'undefined' && item.Month !== null && !isNaN(parseInt(item.Month)));
const casesByTimeKey = {}; // To store aggregated cases by time period (year or year-month)
// Aggregate data by time key
data.forEach(item => {
const year = parseInt(item.Year);
const month = parseInt(item.Month);
let timeKey;
if (hasMonthData && !isNaN(year) && !isNaN(month) && month >= 1 && month <= 12) {
timeKey = `${year}-${String(month).padStart(2, '0')}`; // YYYY-MM format
} else if (!isNaN(year)) {
timeKey = String(year); // Year only
} else {
return; // Skip if no valid year
}
if (!casesByTimeKey[timeKey]) casesByTimeKey[timeKey] = 0;
casesByTimeKey[timeKey] += (Number(item.Cases) || 0);
});
const timeKeys = Object.keys(casesByTimeKey).sort(); // Sort time keys chronologically
// Handle cases where no time keys could be generated
if (timeKeys.length === 0 && data.length > 0) {
displayChartError(lineChartCanvas, 'Could not generate time series from data.');
return;
}
if (timeKeys.length === 0) {
displayChartError(lineChartCanvas, 'No time series data to display for current filters.');
return;
}
// Prepare chart data and options
const chartData = {
labels: timeKeys,
datasets: [{
label: 'Cases',
data: timeKeys.map(key => casesByTimeKey[key]),
borderColor: 'rgba(16, 185, 129, 0.8)', // Tailwind green-500
backgroundColor: 'rgba(16, 185, 129, 0.2)',
fill: true,
tension: 0.1 // Slight curve to the line
}]
};
const chartOptions = {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: { display: true, position: 'top' },
title: { display: true, text: 'Cases Over Time' },
tooltip: {
callbacks: {
label: function(context) {
return `${context.dataset.label}: ${context.parsed.y.toLocaleString()}`;
}
}
}
},
scales: {
x: { title: { display: true, text: hasMonthData ? 'Year-Month' : 'Year' } },
y: { title: { display: true, text: 'Number of Cases' }, beginAtZero: true, ticks: { callback: value => value.toLocaleString() } }
}
};
// Create the new line chart
lineChartInstance = new Chart(lineChartCanvas, {
type: 'line',
data: chartData,
options: chartOptions
});
}
// --- RUN INITIALIZATION ON PAGE LOAD ---
// This ensures the script runs after the full HTML document is parsed and ready.
document.addEventListener('DOMContentLoaded', initializeDashboard);
</script>
</body>
</html>