-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsdeMaps.js
More file actions
2197 lines (1940 loc) · 93.1 KB
/
sdeMaps.js
File metadata and controls
2197 lines (1940 loc) · 93.1 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
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
let permanentTooltipLayer;
let isHeatmapMode = false;
let activeContaminant = null;
let allMapMarkers = [];
let allMapData = { isReady: false };
//let map;
let baseLayers = {};
let datasetLayers = {};
let overlayLayers = {};
let contaminantLayers = {};
let contaminantStats = {};
let contaminantHeatmaps = {};
let dateColors = {};
let markers = {};
let sampleDepths = {};
let depthStatsGlobal = { min: Infinity, max: -Infinity };
let depthSortedSampleIds = [];
let minLat = null, maxLat = null, minLon = null, maxLon = null;
let noLocations = 0, latSum = 0, lonSum = 0;
const hoverStyle = { radius: 10, weight: 3, opacity: 1, fillOpacity: 1 };
let allShapeLayers = [];
let areaTooltipsVisible = false;
let colorMode = 'scale';
let upperLevelMode = '10x';
let shapesColoredByData = false;
let includeShapesOnStaticMaps = false;
let markerScaling = 1;
const highlightStyle = {
radius: 10, fillColor: '#FFFF00', color: '#000000', weight: 2, opacity: 1, fillOpacity: 1
};
function applyDynamicStyling(chemicalName, zoomLevel = null) {
const stats = contaminantStats[chemicalName];
if (!stats) return;
const { valueMin, valueMax, depthMin, depthMax } = stats;
const { breaks, colors } = getColorScale(valueMin * stats.rescale, valueMax * stats.rescale, chemicalName);
contaminantLayers[chemicalName].eachLayer(marker => {
const value = parseFloat(marker.options._chemValue);
const depth = marker.options._depth;
let color = colors[0];
for (let i = breaks.length; i > 0; i--) {
if (value > breaks[i-1]) {
color = colors[i] || colors[colors.length - 1];
break;
}
}
const radius = getLogDepthRadius3Levels(depth, depthMin, depthMax, zoomLevel);
marker.setStyle({ fillColor: color, radius });
});
}
function getColorScale(min, max, chemicalName) {
let breaks = [];
let colors = [];
let levels = null;
if (colorMode === 'standards' && standards[chosenStandard]?.chemicals?.[chemicalName]) {
if(!standards[chosenStandard].chemicals[chemicalName]?.definition) {
levels = standards[chosenStandard].chemicals[chemicalName];
} else {
if(standards[chosenStandard].chemicals[chemicalName]?.levels){
levels = standards[chosenStandard].chemicals[chemicalName].levels;
}
}
}
if (!levels) {
breaks = [
min + (max - min) * 0.25,
min + (max - min) * 0.50,
min + (max - min) * 0.75
];
colors = ["#1a9850", "#fee08b", "#fc8d59", "#d73027"];
} else {
levels = [...levels];
if (levels[1] === null) {
if (upperLevelMode === '10x') {
levels[1] = levels[0] * 10;
colors = ["#00FF00", "#FF0000", "#000000"];
} else {
levels = [levels[0]];
colors = ["#00FF00", "#FF0000"];
}
} else {
colors = ["#00FF00", "#FF0000", "#000000"];
}
const unitAlign = factorUnit(contaminantStats[chemicalName].unit, extractUnit(standards[chosenStandard].unit));
if (unitAlign !== 1) {
levels = levels.map(l => l / unitAlign);
}
breaks = levels;
}
return { breaks, colors };
}
function getHeatmapColor(intensity) {
if (intensity <= 0.2) return '#1a9850';
if (intensity <= 0.4) return '#fee08b';
if (intensity <= 0.6) return '#fc8d59';
if (intensity <= 0.8) return '#f46d43';
return '#d73027';
}
function getLogDepthRadius3Levels(depth, depthMin, depthMax, zoomLevel = null) {
// Define geographic sizes in meters for each depth level
const rSmallMeters = 5; // 5 meters for shallow samples
const rMedMeters = 10; // 10 meters for medium depth samples
const rLargeMeters = 15; // 15 meters for deep samples
let radiusInMeters;
if (depth == null || isNaN(depth) || depthMin === depthMax) {
radiusInMeters = rSmallMeters;
} else {
const logMin = Math.log((depthMin ?? 0) + 1);
const logMax = Math.log((depthMax ?? 0) + 1);
const logVal = Math.log(depth + 1);
const t = (logVal - logMin) / (logMax - logMin);
if (t <= 1 / 3) radiusInMeters = rSmallMeters;
else if (t <= 2 / 3) radiusInMeters = rMedMeters;
else radiusInMeters = rLargeMeters;
}
// Convert meters to pixels based on zoom level
if (zoomLevel === null) {
// Fallback to pixel-based sizing
if (radiusInMeters === rSmallMeters) return 6 * markerScaling;
if (radiusInMeters === rMedMeters) return 12 * markerScaling;
return 18 * markerScaling;
}
// Meters per pixel calculation
const metersPerPixel = 40075017 / (256 * Math.pow(2, zoomLevel)) * Math.cos(54.596 * Math.PI / 180);
// FIX: Scale the result by 20 so the physical meter size translates to visible pixels
return (radiusInMeters / metersPerPixel) * 20 * markerScaling;
}
/*srg251130 function getLogDepthRadius3Levels(depth, depthMin, depthMax, zoomLevel = null) {
// Define geographic sizes in meters for each depth level
const rSmallMeters = 5; // 5 meters for shallow samples
const rMedMeters = 10; // 10 meters for medium depth samples
const rLargeMeters = 15; // 15 meters for deep samples
let radiusInMeters;
if (depth == null || isNaN(depth) || depthMin === depthMax) {
radiusInMeters = rSmallMeters;
} else {
const logMin = Math.log((depthMin ?? 0) + 1);
const logMax = Math.log((depthMax ?? 0) + 1);
const logVal = Math.log(depth + 1);
const t = (logVal - logMin) / (logMax - logMin);
if (t <= 1 / 3) radiusInMeters = rSmallMeters;
else if (t <= 2 / 3) radiusInMeters = rMedMeters;
else radiusInMeters = rLargeMeters;
}
// Convert meters to pixels based on zoom level
// If no zoom level provided, use default pixel sizes
if (zoomLevel === null) {
// Fallback to pixel-based sizing
if (radiusInMeters === rSmallMeters) return 6;
if (radiusInMeters === rMedMeters) return 12;
return 18;
}
// At equator: 1 degree ≈ 111,320 meters
// Meters per pixel = (equator circumference) / (256 * 2^zoom)
// = 40075017 / (256 * 2^zoom)
const metersPerPixel = 40075017 / (256 * Math.pow(2, zoomLevel)) * Math.cos(54.596 * Math.PI / 180);
// Convert radius from meters to pixels
return radiusInMeters / metersPerPixel; // Scale factor for visibility
}
*/
function factorUnit(unit1,unit2) {
const unitScales = {
'g/kg': 1,
'mg/kg': 1e-3,
'µg/kg': 1e-6,
'ng/kg': 1e-9,
'pg/kg': 1e-12,
'fg/kg': 1e-15,
};
return unitScales[unit1] / unitScales[unit2];
}
function extractUnit(string) {
// Define the units to search for in order of specificity
const units = ['µg/kg', 'mg/kg', 'ng/kg', 'pg/kg', 'fg/kg', 'g/kg'];
// Convert string to lowercase for case-insensitive matching
const lowerString = string.toLowerCase();
// Check each unit
for (const unit of units) {
if (lowerString.includes(unit.toLowerCase())) {
return unit;
}
}
// Return null if no unit found
return null;
}
function oneextractUnit(str) {
const regex = /\((µg\/kg)\s*dry weight\)|(mg\/kg)/;
const match = str.match(regex);
if (match) {
return match[1] || match[2] || 'Unit not found';
}
return 'Unit not found';
}
const openStreetMapTiles = L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 19, attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors' });
const worldImageryTiles = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', { maxZoom: 19, attribution: 'Tiles © Esri — Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community.' });
const currentTime = new Date();
const year = currentTime.getFullYear();
const apiKey = 'WYvhmkLwjzAF0LgSL14P7y1v5fySAYy9';
const serviceUrl = 'https://api.os.uk/maps/raster/v1/zxy';
const osRoadTiles = L.tileLayer(`${serviceUrl}/Road_3857/{z}/{x}/{y}.png?key=${apiKey}`, { maxZoom: 19, attribution: 'Contains OS Data © Crown copyright and database rights ' + year });
const osOutdoorTiles = L.tileLayer(`${serviceUrl}/Outdoor_3857/{z}/{x}/{y}.png?key=${apiKey}`, { maxZoom: 19, attribution: 'Contains OS Data © Crown copyright and database rights ' + year });
const openStreetMapHOTTiles = L.tileLayer('https://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png', { maxZoom: 19, attribution: '© OpenStreetMap contributors, Tiles style by Humanitarian OpenStreetMap Team hosted by OpenStreetMap France' });
const openTopoMapTiles = L.tileLayer('https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png', { maxZoom: 19, attribution: 'Map data: © OpenStreetMap contributors, SRTM | Map style: © OpenTopoMap (CC-BY-SA)' });
const openSensorCommunityTiles = L.tileLayer('https://osmc3.maps.sensor.community/{z}/{x}/{y}.png', { maxZoom: 19, attribution: 'Map data: © OpenStreetMap contributors, SRTM | Map style: © Sensor Community' });
function createGlobalLayers() {
console.log('Creating global layers...');
contaminantLayers = {};
contaminantHeatmaps = {};
let allSamples = [];
let sampleNo = -1;
baseLayers = {
"OpenStreetMap": openStreetMapTiles,
"WorldImagery": worldImageryTiles,
"OS Road": osRoadTiles,
"OS Outdoor": osOutdoorTiles,
"OpenStreetMap.HOT": openStreetMapHOTTiles,
"OpenTopoMap": openTopoMapTiles,
"OpenSensorCommunity": openSensorCommunityTiles
};
let colorIndex = 0;
let noSamples = 0;
const datesSampled = Object.keys(selectedSampleInfo);
datesSampled.forEach(dateSampled => {
markers[dateSampled] = {};
dateColors[dateSampled] = markerColors[colorIndex];
colorIndex = (colorIndex + 1) % markerColors.length;
const dsSamples = Object.keys(selectedSampleInfo[dateSampled].position);
noSamples += dsSamples.length;
dsSamples.forEach(sample => allSamples.push(`${dateSampled}: ${sample}`));
});
if(datesSampled.length > 1) {
datesSampled.sort((a, b) => {
const labelA = selectedSampleInfo[a].label || a;
const labelB = selectedSampleInfo[b].label || b;
return labelA.localeCompare(labelB);
});
}
datesSampled.forEach(dateSampled => {
const dsSamples = Object.keys(selectedSampleInfo[dateSampled].position);
dsSamples.forEach(sample => {
const depthInfo = selectedSampleInfo[dateSampled].position[sample]['Sampling depth (m)'];
if (depthInfo) {
const maxDepth = depthInfo['maxDepth'];
if (!isNaN(maxDepth)) {
if (depthStatsGlobal.max === null) {
depthStatsGlobal.min = maxDepth;
depthStatsGlobal.max = maxDepth;
}
const key = `${dateSampled}: ${sample}`;
sampleDepths[key] = maxDepth;
if (maxDepth < depthStatsGlobal.min) depthStatsGlobal.min = maxDepth;
if (maxDepth > depthStatsGlobal.max) depthStatsGlobal.max = maxDepth;
}
}
});
});
//console.log('sampleDepths:', sampleDepths);
//console.log('depthStatsGlobal:', depthStatsGlobal);
function computeIndividualStats(statsByChem, unit, values, chemicalName, lookupName = chemicalName) {
//console.log('computeIndividualStats called with:', chemicalName, 'sample keys:', Object.keys(values || {}));
if (!statsByChem?.[chemicalName]) {
statsByChem[chemicalName] = {};
statsByChem[chemicalName] = {
valueMin: Infinity, valueMax: -Infinity,
depthMin: Infinity, depthMax: -Infinity,
unit: unit
};
} else if (unit && !statsByChem[chemicalName].unit) {
statsByChem[chemicalName].unit = unit;
}
Object.keys(values || {}).forEach(sampleName => {
const value = values[sampleName];
if (value != null && !isNaN(value)) {
if (value < statsByChem[chemicalName].valueMin) statsByChem[chemicalName].valueMin = value;
if (value > statsByChem[chemicalName].valueMax) statsByChem[chemicalName].valueMax = value;
}
// Get depth for this sample
const depth = sampleDepths[sampleName];
//console.log('Looking up depth for:', sampleName, 'found:', depth);
if (depth != null && !isNaN(depth)) {
if (depth < statsByChem[chemicalName].depthMin) statsByChem[chemicalName].depthMin = depth;
if (depth > statsByChem[chemicalName].depthMax) statsByChem[chemicalName].depthMax = depth;
}
});
const { valueMax } = statsByChem[chemicalName];
if (valueMax === -Infinity || valueMax === Infinity || valueMax === 0) {
return statsByChem;
}
//console.log('Stats for', chemicalName, ':', statsByChem[chemicalName]);
return statsByChem
}
function computeContaminationStats() {
let statsByChem = {};
//console.log('selectedSampleMeasurements datasets:', Object.keys(selectedSampleMeasurements));
// Process each dataset separately to maintain sample name context
Object.keys(selectedSampleMeasurements).forEach(datasetName => {
const dataset = selectedSampleMeasurements[datasetName];
//console.log('Processing dataset:', datasetName);
Object.keys(dataset).forEach(sheetName => {
const sheet = dataset[sheetName];
if (!sheet?.chemicals) return;
const unit = extractUnit(sheet['Unit of measurement']);
if (sheet?.total) {
const total = sheet.total;
// Prefix sample names with dataset name to match sampleDepths keys
const prefixedTotal = {};
for (const sample in total) {
prefixedTotal[`${datasetName}: ${sample}`] = total[sample];
}
//console.log('Total samples with prefix:', Object.keys(prefixedTotal));
statsByChem = computeIndividualStats(statsByChem, unit, prefixedTotal, 'Total ' + sheetName);
}
if (sheetName === 'PAH data'){
let lmwSum = {};
let hmwSum = {};
const gorham = sheet.gorhamTest;
for(const sample in gorham) {
lmwSum[`${datasetName}: ${sample}`] = gorham[sample].lmwSum;
hmwSum[`${datasetName}: ${sample}`] = gorham[sample].hmwSum;
}
statsByChem = computeIndividualStats(statsByChem, unit, lmwSum, 'LMW PAH Sum');
statsByChem = computeIndividualStats(statsByChem, unit, hmwSum, 'HMW PAH Sum');
}
if (sheetName === 'PCB data'){
let ices7 = {};
let all = {};
const pcbSums = sheet.congenerTest;
//console.log('PCB samples with prefix:',datasetName, pcbSums);
for(const sample in pcbSums) {
//console.log('datasetName:', datasetName, 'sample:', sample, 'ICES7:', pcbSums[sample].ICES7, 'All:', pcbSums[sample].All);
ices7[`${datasetName}: ${sample}`] = pcbSums[sample].ICES7;
all[`${datasetName}: ${sample}`] = pcbSums[sample].All;
}
statsByChem = computeIndividualStats(statsByChem, unit, ices7, 'ICES7 PCB Sum');
statsByChem = computeIndividualStats(statsByChem, unit, all, 'All PCB Sum');
}
Object.keys(sheet.chemicals).forEach(chemicalName => {
const chemical = sheet.chemicals[chemicalName];
// Prefix sample names with dataset name to match sampleDepths keys
const prefixedSamples = {};
for (const sample in chemical.samples) {
prefixedSamples[`${datasetName}: ${sample}`] = chemical.samples[sample];
}
//console.log('Chemical', chemicalName, 'samples with prefix:', Object.keys(prefixedSamples));
statsByChem = computeIndividualStats(statsByChem, unit, prefixedSamples, chemicalName);
});
});
});
Object.keys(statsByChem).forEach(chemicalName => {
const s = statsByChem[chemicalName];
if (s.valueMin === Infinity) s.valueMin = 0;
if (s.valueMax === -Infinity) s.valueMax = 0;
if (s.depthMin === Infinity) s.depthMin = depthStatsGlobal.min || 0;
if (s.depthMax === -Infinity) s.depthMax = depthStatsGlobal.max || 0;
const valueMax = s.valueMax;
const unitScales = {
'g/kg': 1,
'mg/kg': 1e-3,
'µg/kg': 1e-6,
'ng/kg': 1e-9,
'pg/kg': 1e-12,
'fg/kg': 1e-15
};
const currentUnit = s.unit;
const currentScaleFactor = unitScales[currentUnit];
let bestRescale = 1;
let bestUnit = currentUnit;
let bestFitFound = false;
if (!(valueMax > 1.0 && valueMax <= 1001.0)) {
const valueMaxInG = valueMax * currentScaleFactor;
for (const [newUnit, scaleFactor] of Object.entries(unitScales)) {
const scaledValue = valueMaxInG / scaleFactor;
if ((scaledValue) > 1.0 && (scaledValue <= 1001)) {
bestRescale = currentScaleFactor / scaleFactor;
bestUnit = newUnit;
bestFitFound = true;
break;
}
}
}
statsByChem[chemicalName].rescale = bestRescale;
if (bestFitFound) {
statsByChem[chemicalName].unit = bestUnit;
}
});
return statsByChem;
}
depthSortedSampleIds = Object.keys(sampleDepths).sort((a, b) => {
return sampleDepths[b] - sampleDepths[a];
});
// delete current max lat etc to account if samples have been added or deleted
minLat = null, maxLat = null, minLon = null, maxLon = null;
depthSortedSampleIds.forEach(fullSample => {
let parts = fullSample.split(": ");
if (parts.length > 2) parts[1] = parts[1] + ': ' + parts[2];
const dateSampled = parts[0];
const sample = parts[1];
const currentColor = dateColors[dateSampled];
//console.log(`Processing sample: ${fullSample} (Date: ${dateSampled}, Sample: ${sample})`);
if (selectedSampleInfo[dateSampled]?.position[sample]?.hasOwnProperty('Position latitude')) {
const lat = parseFloat(selectedSampleInfo[dateSampled].position[sample]['Position latitude']);
const lon = parseFloat(selectedSampleInfo[dateSampled].position[sample]['Position longitude']);
if (!isNaN(lat) && !isNaN(lon)) {
if (maxLat === null) { minLat = lat; maxLat = lat; minLon = lon; maxLon = lon; }
else {
if (lat > maxLat) maxLat = lat; else if (lat < minLat) minLat = lat;
if (lon > maxLon) maxLon = lon; else if (lon < minLon) minLon = lon;
}
sampleNo += 1;
const dateLabel = selectedSampleInfo[dateSampled].label;
const sampleLabel = selectedSampleInfo[dateSampled].position[sample].label;
const alternateName = `${dateLabel}: ${sampleLabel}`;
const depth = sampleDepths[fullSample];
const radius = getDepthRadius(depth, depthStatsGlobal.min, depthStatsGlobal.max);
const originalCircleOptions = {
radius: radius, fillColor: currentColor, color: "#000", weight: 1, opacity: 1, fillOpacity: 0.9
};
marker = L.circleMarker([lat, lon], originalCircleOptions)
.bindTooltip(alternateName);
marker.options.customId = fullSample;
marker.options.originalStyle = originalCircleOptions;
marker.options.isHighlighted = false;
marker.on('click', (e) => createHighlights(e.target.options.customId));
highlightMarkers[fullSample] = L.circleMarker(new L.LatLng(lat, lon), highlightStyle).bindTooltip(alternateName);
highlightMarkers[fullSample].options.customId = fullSample;
highlightMarkers[fullSample].on('click', (e) => createHighlights(e.target.options.customId));
noLocations += 1;
latSum += lat;
lonSum += lon;
}
} else {
sampleNo += 1;
highlightMarkers[fullSample] = null;
}
markers[dateSampled][fullSample] = marker;
if (marker) {
allMapMarkers.push(marker);
const alternateName = marker.getTooltip().getContent();
const permanentMarkerStyle = { ...marker.options.originalStyle, interactive: false };
const permanentMarker = L.circleMarker(marker.getLatLng(), permanentMarkerStyle);
permanentMarker.bindTooltip(alternateName, { permanent: true, direction: 'auto', className: 'no-overlap-tooltip' });
}
});
let markerLayers = {};
datesSampled.forEach(dateSampled => {
markerLayers[dateSampled] = [];
const dsKeys = Object.keys(markers[dateSampled]);
dsKeys.forEach(sampleKey => {
if (markers[dateSampled][sampleKey]) markerLayers[dateSampled].push(markers[dateSampled][sampleKey]);
});
});
datasetLayers = {};
datesSampled.forEach(dateSampled => {
datasetLayers[dateSampled] = L.layerGroup(markerLayers[dateSampled]);
});
//console.log(sampleMeasurements);
contaminantStats = computeContaminationStats();
let contaminantMarkerData = {};
// Build a lookup of all chemical values by sample (with full sample names)
let allChemicalValues = {};
Object.keys(selectedSampleMeasurements).forEach(datasetName => {
const dataset = selectedSampleMeasurements[datasetName];
Object.keys(dataset).forEach(sheetName => {
const sheet = dataset[sheetName];
if (!sheet?.chemicals) return;
if (sheet?.total) {
const chemicalName = 'Total ' + sheetName;
if (!allChemicalValues[chemicalName]) allChemicalValues[chemicalName] = {};
for (const sample in sheet.total) {
const fullSampleName = `${datasetName}: ${sample}`;
allChemicalValues[chemicalName][fullSampleName] = sheet.total[sample];
}
}
if (sheetName === 'PAH data'){
const gorham = sheet.gorhamTest;
if (!allChemicalValues['LMW PAH Sum']) allChemicalValues['LMW PAH Sum'] = {};
if (!allChemicalValues['HMW PAH Sum']) allChemicalValues['HMW PAH Sum'] = {};
for(const sample in gorham) {
const fullSampleName = `${datasetName}: ${sample}`;
allChemicalValues['LMW PAH Sum'][fullSampleName] = gorham[sample].lmwSum;
allChemicalValues['HMW PAH Sum'][fullSampleName] = gorham[sample].hmwSum;
}
}
if (sheetName === 'PCB data'){
const pcbSums = sheet.congenerTest;
if (!allChemicalValues['ICES7 PCB Sum']) allChemicalValues['ICES7 PCB Sum'] = {};
if (!allChemicalValues['All PCB Sum']) allChemicalValues['All PCB Sum'] = {};
for(const sample in pcbSums) {
const fullSampleName = `${datasetName}: ${sample}`;
allChemicalValues['ICES7 PCB Sum'][fullSampleName] = pcbSums[sample].ICES7;
allChemicalValues['All PCB Sum'][fullSampleName] = pcbSums[sample].All;
}
}
Object.keys(sheet.chemicals).forEach(chemicalName => {
const chemical = sheet.chemicals[chemicalName];
if (!allChemicalValues[chemicalName]) allChemicalValues[chemicalName] = {};
for (const sample in chemical.samples) {
const fullSampleName = `${datasetName}: ${sample}`;
allChemicalValues[chemicalName][fullSampleName] = chemical.samples[sample];
}
});
});
});
// Now create layers for each chemical, processing all samples in depth order
Object.keys(allChemicalValues).forEach(chemicalName => {
createContaminantLayer(chemicalName, allChemicalValues[chemicalName]);
});
function createContaminantLayer(chemicalName, sampleValues) {
if (!contaminantLayers[chemicalName]) contaminantLayers[chemicalName] = L.layerGroup();
if (!contaminantMarkerData[chemicalName]) contaminantMarkerData[chemicalName] = [];
const stats = contaminantStats[chemicalName];
if (!stats) return;
const unit = stats.unit;
const depthMin = stats.depthMin;
const depthMax = stats.depthMax;
//console.log(`createContaminantLayer for ${chemicalName}: depthMin=${depthMin}, depthMax=${depthMax}`);
// Process samples in depth order (deepest first) - THIS IS THE KEY FIX
depthSortedSampleIds.forEach(fullSampleName => {
const value = sampleValues[fullSampleName];
if (value == null || isNaN(value)) return;
const rescaledValue = value * stats.rescale;
// Parse the fullSampleName to get dataset and sample
let parts = fullSampleName.split(": ");
if (parts.length > 2) parts = [parts[0], parts.slice(1).join(": ")];
const datasetName = parts[0];
const sampleName = parts[1];
const sampleInfo = selectedSampleInfo[datasetName]?.position?.[sampleName];
if (!sampleInfo) return;
const lat = parseFloat(sampleInfo["Position latitude"]);
const lon = parseFloat(sampleInfo["Position longitude"]);
if (isNaN(lat) || isNaN(lon)) return;
const depth = sampleDepths[fullSampleName];
const initialRadius = getLogDepthRadius3Levels(depth, depthMin, depthMax);
//console.log(`${chemicalName} - Sample: ${fullSampleName}, Depth: ${depth}, Radius: ${initialRadius}`);
const sampleLabel = selectedSampleInfo[datasetName]?.label + ' : ' + sampleInfo.label;
const unitSuffix = unit ? ` ${unit}` : "";
const tooltipHtml = `${sampleLabel}<br>${chemicalName}: ${rescaledValue.toFixed(2)}${unitSuffix}<br>Depth: ${depth} m`;
const m = L.circleMarker([lat, lon], {
radius: initialRadius,
fillColor: "#999",
color: "#000",
weight: 1,
opacity: 1,
fillOpacity: 0.8
}).bindTooltip(tooltipHtml);
m.options._chemValue = rescaledValue.toFixed(2);
m.options._chemUnit = unit || "";
m.options._depth = depth;
m.options.customId = fullSampleName;
contaminantLayers[chemicalName].addLayer(m);
contaminantMarkerData[chemicalName].push(m);
});
}
Object.keys(contaminantLayers).forEach(chem => applyDynamicStyling(chem));
Object.keys(contaminantMarkerData).forEach(chemicalName => {
const items = contaminantMarkerData[chemicalName];
if (!items || items.length === 0) return;
const stats = contaminantStats[chemicalName];
if (!stats) return;
const heatmapLayer = L.layerGroup();
items.sort((a, b) => (b.options._depth ?? -1) - (a.options._depth ?? -1)).forEach(marker => {
const point = {
lat: marker.getLatLng().lat,
lng: marker.getLatLng().lng,
value: marker.options._chemValue,
depth: marker.options._depth
};
if (isNaN(point.lat) || isNaN(point.lng)) return;
const normalizedLevel = Math.min((point.value - stats.valueMin) / (stats.valueMax - stats.valueMin || 1), 1);
for (let i = 3; i >= 1; i--) {
let baseRadius = (point.depth != null && !isNaN(point.depth)) ? 100 + (getLogDepthRadius3Levels(point.depth, stats.depthMin, stats.depthMax) - 6) * 5 : 100;
const layerScale = 0.3 + (i - 1) * 0.35;
const valueScale = 0.5 + normalizedLevel * 1.0;
const radius = baseRadius * layerScale * valueScale;
const opacity = (0.4 / i) * (0.4 + normalizedLevel * 0.8);
const color = getHeatmapColor(normalizedLevel);
L.circle([point.lat, point.lng], {
radius: radius,
fillColor: color,
color: 'transparent',
fillOpacity: opacity,
weight: 0
}).addTo(heatmapLayer);
}
});
contaminantHeatmaps[chemicalName] = heatmapLayer;
});
allMapData.isReady = true;
allMapData.contaminantLayers = contaminantLayers;
allMapData.contaminantHeatmaps = contaminantHeatmaps;
allMapData.contaminantStats = contaminantStats;
}
function forceMapRefresh(containerId) {
const container = document.getElementById(containerId);
if (container && container._leaflet_map) {
const map = container._leaflet_map;
setTimeout(() => {
map.invalidateSize(true);
setTimeout(() => {
map.invalidateSize({ pan: false });
setTimeout(() => {
map.invalidateSize(true);
map.eachLayer(layer => {
if (layer._url) {
layer.redraw();
}
});
}, 50);
}, 50);
}, 50);
}
}
function ClaudeV4createStaticContaminantMap(containerId, contaminantName, visualizationType = 'points', mapTile = 'OpenStreetMap') {
if (!allMapData.isReady) {
console.error("Data not yet processed. Call createGlobalLayers first.");
return;
}
const container = document.getElementById(containerId);
if (!container) {
console.error(`Container with ID '${containerId}' not found.`);
return;
}
if (container._leaflet_id !== undefined) {
console.log(`Removing existing map from container with ID: ${containerId}`);
container._leaflet_map.remove();
delete container._leaflet_map;
}
const staticMap = L.map(containerId, {
center: [54.596, -1.177],
zoom: 13,
zoomControl: false,
attributionControl: false,
scrollWheelZoom: false,
doubleClickZoom: false,
boxZoom: false,
keyboard: false,
dragging: false,
});
container._leaflet_map = staticMap;
const baseLayerInstance = baseLayers[mapTile] || baseLayers['OpenStreetMap'];
const tileLayerUrl = baseLayerInstance._url;
const tileLayerOptions = baseLayerInstance.options;
L.tileLayer(tileLayerUrl, tileLayerOptions).addTo(staticMap);
let layerToAdd;
if (visualizationType === 'points' && allMapData.contaminantLayers[contaminantName]) {
layerToAdd = L.layerGroup();
allMapData.contaminantLayers[contaminantName].eachLayer(layer => {
const clonedLayer = L.circleMarker(layer.getLatLng(), { ...layer.options });
if (layer.getTooltip()) {
clonedLayer.bindTooltip(layer.getTooltip().getContent(), { ...layer.getTooltip().options });
}
layerToAdd.addLayer(clonedLayer);
});
} else if (visualizationType === 'heatmap' && allMapData.contaminantHeatmaps[contaminantName]) {
layerToAdd = L.layerGroup();
allMapData.contaminantHeatmaps[contaminantName].eachLayer(layer => {
layerToAdd.addLayer(L.circle(layer.getLatLng(), { ...layer.options }));
});
}
if (layerToAdd) {
layerToAdd.addTo(staticMap);
//srg251130 --- CHANGE START ---
// 1. Add listeners to this static map to update marker sizes on zoom/resize
staticMap.on('zoomend resize', function() {
// Only apply styling if we are in 'points' mode (not heatmap)
if (visualizationType === 'points') {
applyDynamicStyling(contaminantName, staticMap.getZoom());
}
});
// --- CHANGE END ---
const bounds = new L.LatLngBounds([]);
layerToAdd.eachLayer(layer => {
if (layer.getLatLng) {
bounds.extend(layer.getLatLng());
}
});
if (bounds.isValid()) {
setTimeout(() => {
container.offsetWidth;
staticMap.invalidateSize();
staticMap.fitBounds(bounds, { padding: [20, 20] });
//srg251130 --- CHANGE START ---
// 2. Force an immediate style update after the bounds are fitted
if (visualizationType === 'points') {
// We calculate the target zoom manually or grab it after a short delay
// The most reliable way here is to run it in the same timeout stack
applyDynamicStyling(contaminantName, staticMap.getBoundsZoom(bounds));
}
// --- CHANGE END ---
}, 150);
}
} else {
console.warn(`Contaminant layer '${contaminantName}' of type '${visualizationType}' not found.`);
}
}
function createStaticContaminantMap(containerId, contaminantName, visualizationType = 'points', showLegend = false , mapTile = 'OpenStreetMap') {
if (!allMapData.isReady) {
console.error("Data not yet processed. Call createGlobalLayers first.");
return;
}
const container = document.getElementById(containerId);
if (!container) {
console.error(`Container with ID '${containerId}' not found.`);
return;
}
if (container._leaflet_id !== undefined) {
console.log(`Removing existing map from container with ID: ${containerId}`);
container._leaflet_map.remove();
delete container._leaflet_map;
}
let mapCreated = false;
const resizeObserver = new ResizeObserver((entries) => {
entries.forEach(entry => {
const { width, height } = entry.contentRect;
console.log(`Container ${containerId} resized to: ${width}x${height}`);
if (!mapCreated && width > 100 && height > 100) {
mapCreated = true;
resizeObserver.disconnect();
console.log(`Creating map for ${containerId} with dimensions ${width}x${height}`);
const staticMap = L.map(containerId, {
center: [54.596, -1.177],
zoom: 13,
zoomControl: false,
attributionControl: false,
scrollWheelZoom: false,
doubleClickZoom: false,
boxZoom: false,
keyboard: false,
dragging: false,
});
container._leaflet_map = staticMap;
const baseLayerInstance = baseLayers[mapTile] || baseLayers['OpenStreetMap'];
const tileLayerUrl = baseLayerInstance._url;
const tileLayerOptions = baseLayerInstance.options;
L.tileLayer(tileLayerUrl, tileLayerOptions).addTo(staticMap);
let layerToAdd;
if (visualizationType === 'points' && contaminantLayers[contaminantName]) {
layerToAdd = L.layerGroup();
contaminantLayers[contaminantName].eachLayer(layer => {
if (layer instanceof L.CircleMarker) {
const options = { ...layer.options };
if (options.radius) {
options.radius = options.radius * 0.3;
}
const clonedLayer = L.circleMarker(layer.getLatLng(), options);
layerToAdd.addLayer(clonedLayer);
}
});
} else if (visualizationType === 'heatmap' && contaminantHeatmaps[contaminantName]) {
layerToAdd = contaminantHeatmaps[contaminantName];
}
if (layerToAdd) {
layerToAdd.addTo(staticMap);
const bounds = new L.LatLngBounds([]);
layerToAdd.eachLayer(layer => {
if (layer.getLatLng) {
bounds.extend(layer.getLatLng());
}
});
if (bounds.isValid()) {
setTimeout(() => {
staticMap.invalidateSize();
staticMap.fitBounds(bounds, { padding: [20, 20] });
}, 50);
}
if (showLegend) {
if (contaminantStats[contaminantName]) {
const legend = L.control({ position: 'leftright' });
legend.onAdd = function () {
const div = L.DomUtil.create('div', 'info legend');
const stats = contaminantStats[contaminantName];
const unit = stats.unit ? ` ${stats.unit}` : "";
const min = stats.valueMin*stats.rescale, max = stats.valueMax*stats.rescale;
const colors = ["#d73027", "#d73027", "#d73027", "#d73027"];
div.innerHTML = `
<h4>${contaminantName}</h4>
<strong>Value</strong>
<div style="
height: 20px;
width: 100%;
background: linear-gradient(to right, ${colors.join(",")});
border: 1px solid #999;
margin-bottom: 5px;
"></div>
<div style="display: flex; justify-content: space-between; font-size: 12px;">
<span>${isFinite(min) ? min.toFixed(2) : '—'}${unit}</span>
<span>${isFinite(max) ? max.toFixed(2) : '—'}${unit}</span>
</div>
`;
return div;
};
legend.addTo(staticMap);
}
}
} else {
console.warn(`Contaminant layer '${contaminantName}' of type '${visualizationType}' not found.`);
}
// Add shapes if enabled
if (includeShapesOnStaticMaps && allShapeLayers.length > 0) {
allShapeLayers.forEach((originalLayer, index) => {
let clonedLayer;
if (originalLayer instanceof L.Polygon) {
clonedLayer = L.polygon(originalLayer.getLatLngs());
} else if (originalLayer instanceof L.Polyline) {
clonedLayer = L.polyline(originalLayer.getLatLngs());
}
if (clonedLayer) {
const style = getShapeStyleForContaminant(originalLayer, contaminantName, index);
clonedLayer.setStyle(style);
clonedLayer.addTo(staticMap);
}
});
}
}
});
});
resizeObserver.observe(container);
}
function sampleMap(meas) {
if (map) map.remove();
isHeatmapMode = false;
activeContaminant = null;
allShapeLayers = [];
const markerColors = ['#FF5733', '#33CFFF', '#33FF57', '#FF33A1', '#A133FF', '#FFC300', '#33FFA1', '#C70039', '#900C3F'];
const datesSampled = Object.keys(selectedSampleInfo);
let colorIndex = 0;
let allSamples = [];
let noSamples = 0;
let markers = {};
let marker = null;
let sampleNo = -1;
dateColors = {};
datesSampled.forEach(dateSampled => {
markers[dateSampled] = {};
dateColors[dateSampled] = markerColors[colorIndex];
colorIndex = (colorIndex + 1) % markerColors.length;
const dsSamples = Object.keys(selectedSampleInfo[dateSampled].position);
noSamples += dsSamples.length;
dsSamples.forEach(sample => allSamples.push(`${dateSampled}: ${sample}`));
});
datesSampled.sort((a, b) => {
const labelA = selectedSampleInfo[a].label || a;
const labelB = selectedSampleInfo[b].label || b;
return labelA.localeCompare(labelB);
});
const legendData = [];
datesSampled.forEach(dateSampled => {
const color = dateColors[dateSampled];
const label = selectedSampleInfo[dateSampled].label || dateSampled;
const svgIcon = `<svg height="18" width="18" xmlns="http://www.w3.org/2000/svg"><circle cx="9" cy="9" r="7" stroke="black" stroke-width="1" fill="${color}" /></svg>`;
const iconUrl = `data:image/svg+xml;base64,${btoa(svgIcon)}`;
legendData.push({ label, iconUrl });
});
populateMapLegend(legendData);
if (!(xAxisSort === 'normal')) {
allSamples.sortComplexSamples();
}
const hoverStyle = { radius: 10, weight: 3, opacity: 1, fillOpacity: 1 };
/* map = L.map('map', {
center: [54.596, -1.177],
zoom: 13,
layers: [baseLayers.OpenStreetMap]
});*/
// ... inside sampleMap(meas) in sdeMaps.js ...
map = L.map('map', {
center: [54.596, -1.177],
zoom: 13,
layers: [baseLayers.OpenStreetMap]
});
// Define a global variable for the control if you haven't already
let layerControl;
// Initialize the control only once
if (!layerControl) {
// (null represents base layers, which we aren't changing here)
layerControl = L.control.layers(null, {}, { collapsed: true }).addTo(map);
}
// --- ADD START: Measurement Tools ---
// 1. Create a FeatureGroup to store the things you draw
var drawnItems = new L.FeatureGroup();
map.addLayer(drawnItems);
// 2. Configure the tools (turn on metric measurements and area display)
var drawControl = new L.Control.Draw({
edit: {
featureGroup: drawnItems
},
draw: {
polyline: {
metric: true, // Shows distance
feet: false // Disable feet to enforce metric system