Repository navigation
Expand file tree
/
Copy pathcompare.html
More file actions
698 lines (633 loc) · 29.9 KB
/
Copy pathcompare.html
File metadata and controls
698 lines (633 loc) · 29.9 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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ESF OpenFrontier - Carbon Data Comparison</title>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4/dist/chart.umd.min.js"></script>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; }
#map { position: absolute; top: 0; left: 0; right: 0; bottom: 0; }
.panel {
position: absolute; top: 12px; z-index: 1000;
background: rgba(255,255,255,0.95); padding: 12px 16px;
border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.3);
display: flex; flex-direction: column; gap: 8px;
min-width: 180px;
}
.panel-left { left: 12px; }
.panel-right { right: 12px; }
.panel-label {
font-size: 11px; font-weight: 700; text-transform: uppercase;
letter-spacing: 0.5px;
}
.panel-left .panel-label { color: #b5179e; }
.panel-right .panel-label { color: #0077b6; }
.panel select {
padding: 6px 8px; border: 2px solid #ccc; border-radius: 6px;
font-size: 13px; font-weight: 600; background: white; cursor: pointer;
}
.panel-left select:focus { border-color: #b5179e; outline: none; }
.panel-right select:focus { border-color: #0077b6; outline: none; }
.panel .year-display {
font-size: 28px; font-weight: 800; text-align: center; line-height: 1;
}
.panel-left .year-display { color: #b5179e; }
.panel-right .year-display { color: #0077b6; }
.panel input[type="range"] { width: 100%; cursor: pointer; }
.panel-left input[type="range"] { accent-color: #b5179e; }
.panel-right input[type="range"] { accent-color: #0077b6; }
.year-endpoints {
display: flex; justify-content: space-between;
font-size: 11px; color: #999; margin-top: -4px;
}
.info-opacity {
display: flex; flex-direction: column; align-items: center; gap: 4px;
margin-top: 6px;
}
.info-opacity .opacity-row {
display: flex; align-items: center; gap: 8px;
}
.info-opacity input[type="range"] {
width: 160px; cursor: pointer; vertical-align: middle;
}
.info-opacity span {
font-size: 12px; font-weight: 600; color: #444; min-width: 32px;
}
/* Swipe divider */
#swipe-bar {
position: absolute; top: 0; bottom: 0; width: 4px;
background: white; z-index: 500; cursor: ew-resize;
box-shadow: 0 0 8px rgba(0,0,0,0.4);
left: 50%;
}
#swipe-handle {
position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);
width: 40px; height: 40px; background: white; border-radius: 50%;
box-shadow: 0 2px 8px rgba(0,0,0,0.4); cursor: ew-resize;
display: flex; align-items: center; justify-content: center;
font-size: 18px; color: #555; user-select: none;
}
/* Colorbar */
.colorbar {
position: absolute; z-index: 1000;
bottom: 50px; right: 12px;
background: rgba(255,255,255,0.95); padding: 10px 12px;
border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.25);
display: flex; align-items: stretch; gap: 8px;
}
.colorbar-gradient {
width: 18px; height: 160px; border-radius: 3px; border: 1px solid #ccc;
background: linear-gradient(to top,
#440154 0%, #482878 12.5%, #3e4989 25%, #31688e 37.5%,
#26828e 50%, #1f9e89 62.5%, #35b779 75%, #6ece58 87.5%,
#fde725 100%);
}
.colorbar-labels {
display: flex; flex-direction: column; justify-content: space-between;
font-size: 11px; font-weight: 600; color: #444;
}
.colorbar-title {
font-size: 11px; font-weight: 700; color: #333;
writing-mode: vertical-rl; text-orientation: mixed;
transform: rotate(180deg);
display: flex; align-items: center; justify-content: center;
}
.info-bar {
position: absolute; bottom: 50px; left: 50%; transform: translateX(-50%);
z-index: 1000; background: rgba(255,255,255,0.9); padding: 8px 20px;
border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.2);
font-size: 13px; color: #555; text-align: center;
}
.info-bar-bottom {
position: absolute; bottom: 12px; left: 50%; transform: translateX(-50%);
z-index: 1000; background: rgba(255,255,255,0.9); padding: 8px 20px;
border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.2);
font-size: 13px; color: #555; text-align: center; white-space: nowrap;
}
.info-bar-bottom kbd {
background: #eee; padding: 2px 6px; border-radius: 3px;
border: 1px solid #ccc; font-size: 12px;
}
.basemap-picker {
display: flex; justify-content: center; gap: 12px;
margin-top: 6px; font-size: 12px; font-weight: 600; color: #333;
}
.basemap-picker label {
display: flex; align-items: center; gap: 6px; cursor: pointer;
}
.info-bar kbd {
background: #eee; padding: 2px 6px; border-radius: 3px;
border: 1px solid #ccc; font-size: 12px;
}
/* Point query popup */
.leaflet-popup-pane { z-index: 1000; }
.leaflet-popup-content { font-family: inherit; font-size: 13px; }
.point-val { font-size: 18px; font-weight: 700; }
.point-label { font-size: 11px; color: #666; }
.point-row { margin-bottom: 6px; }
.point-row:last-child { margin-bottom: 0; }
.point-left { color: #b5179e; }
.point-right { color: #0077b6; }
.point-loading { color: #999; font-style: italic; }
.point-chart { width: 280px; height: 160px; margin-top: 8px; }
/* Mobile responsive */
@media (max-width: 600px) {
.panel {
padding: 4px 6px; gap: 2px; min-width: 90px;
}
.panel-left { left: 2px; }
.panel-right { right: 2px; }
.panel-label { font-size: 7px; letter-spacing: 0.3px; }
.panel select { padding: 2px 3px; font-size: 9px; border-width: 1px; }
.panel .year-display { font-size: 14px; }
.panel input[type="range"] { height: 12px; }
.year-endpoints { font-size: 7px; margin-top: -2px; }
#swipe-handle {
width: 22px; height: 22px; font-size: 11px;
}
#swipe-bar { width: 2px; }
.colorbar { padding: 4px 6px; bottom: 40px; }
.colorbar-gradient { width: 10px; height: 80px; }
.colorbar-labels { font-size: 8px; }
.colorbar-title { font-size: 8px; }
.info-bar { padding: 4px 10px; font-size: 11px; max-width: 90vw; }
.control-label { font-size: 12px !important; }
.info-opacity input[type="range"] { width: 110px; }
.info-opacity span { font-size: 10px; }
.basemap-picker { font-size: 10px; gap: 8px; }
.basemap-picker label { gap: 3px; }
.info-bar-bottom { padding: 4px 10px; font-size: 10px; }
.info-bar-bottom kbd { font-size: 9px; padding: 1px 4px; }
}
</style>
</head>
<body>
<div id="map"></div>
<div id="swipe-bar"><div id="swipe-handle">⬌</div></div>
<div class="panel panel-left">
<span class="panel-label">Left</span>
<select id="var-left">
<option value="agb" selected>AGB - Biomass</option>
<option value="agc">AGC - Carbon</option>
<option value="bgc">BGC - Below Carbon</option>
</select>
<div class="year-display" id="year-left">1990</div>
<input type="range" id="slider-left" min="1990" max="2023" value="1990" step="1">
<div class="year-endpoints"><span>1990</span><span>2023</span></div>
</div>
<div class="panel panel-right">
<span class="panel-label">Right</span>
<select id="var-right">
<option value="agb" selected>AGB - Biomass</option>
<option value="agc">AGC - Carbon</option>
<option value="bgc">BGC - Below Carbon</option>
</select>
<div class="year-display" id="year-right">2023</div>
<input type="range" id="slider-right" min="1990" max="2023" value="2023" step="1">
<div class="year-endpoints"><span>1990</span><span>2023</span></div>
</div>
<div class="colorbar" id="colorbar">
<div class="colorbar-title" id="colorbar-title">AGB (Mg/ha)</div>
<div class="colorbar-gradient"></div>
<div class="colorbar-labels">
<span id="cb-max">250</span>
<span id="cb-mid"></span>
<span id="cb-min">0</span>
</div>
</div>
<div class="info-bar">
<span class="info-opacity">
<span class="control-label" style="font-size: 18px; font-weight: 800; text-align: center; line-height: 1; color: #555;">Overlay Opacity</span>
<span class="opacity-row">
<input type="range" id="opacity-slider" min="0" max="100" value="85" step="1">
<span id="opacity-val">85%</span>
</span>
</span>
<span class="control-label" style="font-size: 18px; font-weight: 800; text-align: center; line-height: 1; color: #555; margin-top: 8px;">Basemap</span>
<div class="basemap-picker">
<label><input type="radio" name="basemap" value="map" checked> Street Map</label>
<label><input type="radio" name="basemap" value="satellite"> Satellite</label>
</div>
</div>
<div class="info-bar-bottom">
Click map for values • Drag handle to compare •
<kbd>←</kbd><kbd>→</kbd> left year •
<kbd>Shift</kbd>+<kbd>←</kbd><kbd>→</kbd> right year
</div>
<script>
const TITILER = 'https://vaiqqtybhb.execute-api.us-east-1.amazonaws.com';
const R2_BUCKET = 'osc';
const VAR_INFO = {
agb: { label: 'AGB', unit: 'Mg/ha', max: 250 },
agc: { label: 'AGC', unit: 'Mg C/ha', max: 125 },
bgc: { label: 'BGC', unit: 'Mg C/ha', max: 75 },
};
const VALID_VARS = ['agb', 'agc', 'bgc'];
// Parse URL hash parameters
function parseHash() {
const params = {};
const hash = window.location.hash.replace(/^#/, '');
if (!hash) return params;
hash.split('&').forEach(part => {
const [k, v] = part.split('=');
if (k && v !== undefined) params[decodeURIComponent(k)] = decodeURIComponent(v);
});
return params;
}
function updateHash() {
const center = map.getCenter();
const parts = [
`lat=${center.lat.toFixed(4)}`,
`lon=${center.lng.toFixed(4)}`,
`z=${map.getZoom()}`,
`lv=${leftVar}`,
`ly=${leftYear}`,
`rv=${rightVar}`,
`ry=${rightYear}`,
`o=${Math.round(layerOpacity * 100)}`,
`base=${currentBasemap === basemapSatellite ? 'satellite' : 'map'}`,
];
history.replaceState(null, '', '#' + parts.join('&'));
}
// Read initial state from hash (with defaults)
const h = parseHash();
const initLat = parseFloat(h.lat) || 42.8;
const initLon = parseFloat(h.lon) || -75.5;
const initZoom = parseInt(h.z) || 7;
const initBase = h.base || 'map';
function tileUrl(variable, year) {
return `${TITILER}/esf/tiles/WebMercatorQuad/{z}/{x}/{y}.png`
+ `?variable=${variable}&time=${year}&colormap_name=viridis`;
}
function cogUrl(variable, year) {
return `s3://${R2_BUCKET}/esf-${variable}/${variable}_${year}_cog.tif`;
}
// Initialize map
const map = L.map('map', { zoomControl: false }).setView([initLat, initLon], initZoom);
L.control.zoom({ position: 'bottomleft' }).addTo(map);
const basemapStreets = L.tileLayer('https://mt1.google.com/vt/lyrs=m&x={x}&y={y}&z={z}', {
attribution: '© Google',
maxZoom: 20
});
const basemapSatellite = L.tileLayer('https://mt1.google.com/vt/lyrs=y&x={x}&y={y}&z={z}', {
attribution: '© Google',
maxZoom: 20
});
let currentBasemap;
if (initBase === 'satellite') {
basemapSatellite.addTo(map);
currentBasemap = basemapSatellite;
document.querySelector('input[name="basemap"][value="satellite"]').checked = true;
} else {
basemapStreets.addTo(map);
currentBasemap = basemapStreets;
}
document.querySelectorAll('input[name="basemap"]').forEach(radio => {
radio.addEventListener('change', () => {
if (radio.value === 'satellite') {
if (currentBasemap === basemapStreets) map.removeLayer(basemapStreets);
basemapSatellite.addTo(map);
basemapSatellite.bringToBack();
currentBasemap = basemapSatellite;
} else {
if (currentBasemap === basemapSatellite) map.removeLayer(basemapSatellite);
basemapStreets.addTo(map);
basemapStreets.bringToBack();
currentBasemap = basemapStreets;
}
updateHash();
});
});
// State (initialized from hash or defaults)
let leftVar = VALID_VARS.includes(h.lv) ? h.lv : 'agb';
let leftYear = (parseInt(h.ly) >= 1990 && parseInt(h.ly) <= 2023) ? parseInt(h.ly) : 1990;
let rightVar = VALID_VARS.includes(h.rv) ? h.rv : 'agb';
let rightYear = (parseInt(h.ry) >= 1990 && parseInt(h.ry) <= 2023) ? parseInt(h.ry) : 2023;
let layerOpacity = (parseInt(h.o) >= 0 && parseInt(h.o) <= 100) ? parseInt(h.o) / 100 : 0.85;
let leftLayer = null, rightLayer = null;
let swipeX = window.innerWidth / 2;
// Sync UI controls to initial state from hash
document.getElementById('var-left').value = leftVar;
document.getElementById('var-right').value = rightVar;
document.getElementById('slider-left').value = leftYear;
document.getElementById('slider-right').value = rightYear;
document.getElementById('opacity-slider').value = Math.round(layerOpacity * 100);
document.getElementById('opacity-val').textContent = Math.round(layerOpacity * 100) + '%';
// Colorbar
function updateColorbar() {
const vars = new Set([leftVar, rightVar]);
if (vars.size === 1) {
const v = VAR_INFO[leftVar];
document.getElementById('colorbar-title').textContent = `${v.label} (${v.unit})`;
document.getElementById('cb-max').textContent = v.max;
document.getElementById('cb-mid').textContent = Math.round(v.max / 2);
document.getElementById('cb-min').textContent = '0';
} else {
const vl = VAR_INFO[leftVar], vr = VAR_INFO[rightVar];
document.getElementById('colorbar-title').textContent = 'viridis';
document.getElementById('cb-max').textContent = `${vl.label}:${vl.max} / ${vr.label}:${vr.max}`;
document.getElementById('cb-mid').textContent = '';
document.getElementById('cb-min').textContent = '0';
}
}
function getClipX() {
const mapRect = map.getContainer().getBoundingClientRect();
const nw = map.containerPointToLayerPoint([0, 0]);
const se = map.containerPointToLayerPoint(map.getSize());
const ratio = (swipeX - mapRect.left) / mapRect.width;
return nw.x + ratio * (se.x - nw.x);
}
function clipLeft() {
if (!leftLayer) return;
const container = leftLayer.getContainer();
if (container) {
const nw = map.containerPointToLayerPoint([0, 0]);
const se = map.containerPointToLayerPoint(map.getSize());
const clipX = getClipX();
container.style.clip = `rect(${nw.y}px, ${clipX}px, ${se.y}px, ${nw.x}px)`;
}
}
function clipRight() {
if (!rightLayer) return;
const container = rightLayer.getContainer();
if (container) {
const nw = map.containerPointToLayerPoint([0, 0]);
const se = map.containerPointToLayerPoint(map.getSize());
const clipX = getClipX();
container.style.clip = `rect(${nw.y}px, ${se.x}px, ${se.y}px, ${clipX}px)`;
}
}
function updateClip() {
clipLeft();
clipRight();
document.getElementById('swipe-bar').style.left = swipeX + 'px';
}
function updateLayers() {
if (leftLayer) map.removeLayer(leftLayer);
if (rightLayer) map.removeLayer(rightLayer);
leftLayer = L.tileLayer(tileUrl(leftVar, leftYear), {
opacity: layerOpacity, attribution: 'ESF / Frontier Geospatial'
}).addTo(map);
rightLayer = L.tileLayer(tileUrl(rightVar, rightYear), {
opacity: layerOpacity, attribution: 'ESF / Frontier Geospatial'
}).addTo(map);
leftLayer.on('load tileload', clipLeft);
rightLayer.on('load tileload', clipRight);
setTimeout(updateClip, 50);
document.getElementById('year-left').textContent = leftYear;
document.getElementById('year-right').textContent = rightYear;
updateColorbar();
updateHash();
}
// Swipe bar dragging
const swipeBar = document.getElementById('swipe-bar');
let dragging = false;
function startDrag(e) {
dragging = true;
e.preventDefault();
map.dragging.disable();
}
function doDrag(e) {
if (!dragging) return;
const clientX = e.touches ? e.touches[0].clientX : e.clientX;
swipeX = Math.max(0, Math.min(window.innerWidth, clientX));
updateClip();
}
function endDrag() {
if (!dragging) return;
dragging = false;
map.dragging.enable();
}
swipeBar.addEventListener('mousedown', startDrag);
swipeBar.addEventListener('touchstart', startDrag);
document.addEventListener('mousemove', doDrag);
document.addEventListener('touchmove', doDrag);
document.addEventListener('mouseup', endDrag);
document.addEventListener('touchend', endDrag);
// Re-clip on map move/zoom and window resize
map.on('move zoom moveend zoomend', updateClip);
map.on('moveend zoomend', updateHash);
window.addEventListener('resize', () => {
swipeX = Math.max(0, Math.min(window.innerWidth, swipeX));
updateClip();
});
// Point query on click
let pointChart = null;
map.on('click', async (e) => {
const { lng, lat } = e.latlng;
const minYear = Math.min(leftYear, rightYear);
const maxYear = Math.max(leftYear, rightYear);
const years = [];
for (let y = minYear; y <= maxYear; y++) years.push(y);
const popup = L.popup({ maxWidth: 350 })
.setLatLng(e.latlng)
.setContent('<span class="point-loading">Loading values...</span>')
.openOn(map);
try {
// Fetch left/right selected years immediately for the text display
const [leftRes, rightRes] = await Promise.all([
fetch(`${TITILER}/cog/point/${lng},${lat}?url=${encodeURIComponent(cogUrl(leftVar, leftYear))}`).then(r => r.json()),
fetch(`${TITILER}/cog/point/${lng},${lat}?url=${encodeURIComponent(cogUrl(rightVar, rightYear))}`).then(r => r.json()),
]);
const leftVal = leftRes.values?.[0];
const rightVal = rightRes.values?.[0];
const vl = VAR_INFO[leftVar], vr = VAR_INFO[rightVar];
function fmt(val) {
if (val === null || val === undefined || val === -9999) return 'No data';
return val.toFixed(1);
}
function isValid(val) {
return val !== null && val !== undefined && val !== -9999;
}
let html = '';
html += `<div class="point-row"><span class="point-label">Coordinates:</span><br><span class="point-label">${lat.toFixed(4)}, ${lng.toFixed(4)}</span></div>`;
html += `<div class="point-row"><span class="point-label point-left">${vl.label} ${leftYear} (Left):</span><br>`;
html += `<span class="point-val point-left">${fmt(leftVal)} ${isValid(leftVal) ? vl.unit : ''}</span></div>`;
html += `<div class="point-row"><span class="point-label point-right">${vr.label} ${rightYear} (Right):</span><br>`;
html += `<span class="point-val point-right">${fmt(rightVal)} ${isValid(rightVal) ? vr.unit : ''}</span></div>`;
if (leftVar === rightVar && isValid(leftVal) && isValid(rightVal)) {
const diff = rightVal - leftVal;
const sign = diff >= 0 ? '+' : '';
html += `<div class="point-row"><span class="point-label">Change:</span><br>`;
html += `<span class="point-val" style="color:${diff >= 0 ? '#2d6a4f' : '#d00'}">${sign}${diff.toFixed(1)} ${vl.unit}</span></div>`;
}
html += '<div class="point-chart"><canvas id="point-chart-canvas"></canvas></div>';
popup.setContent(html);
// Fetch all years for time series chart
const sameVar = leftVar === rightVar;
const varsToFetch = sameVar ? [leftVar] : [leftVar, rightVar];
const seriesData = {};
for (const v of varsToFetch) {
const results = await Promise.all(
years.map(y =>
fetch(`${TITILER}/cog/point/${lng},${lat}?url=${encodeURIComponent(cogUrl(v, y))}`)
.then(r => r.json())
.then(d => d.values?.[0])
.catch(() => null)
)
);
seriesData[v] = results.map(val => isValid(val) ? val : null);
}
// Check popup is still open
const canvas = document.getElementById('point-chart-canvas');
if (!canvas) return;
if (pointChart) { pointChart.destroy(); pointChart = null; }
const datasets = [];
if (sameVar) {
datasets.push({
label: `${vl.label} (${vl.unit})`,
data: seriesData[leftVar],
borderColor: '#b5179e',
backgroundColor: '#b5179e',
borderWidth: 1.5,
pointRadius: 2,
tension: 0,
spanGaps: true,
});
} else {
datasets.push({
label: `${vl.label} (${vl.unit})`,
data: seriesData[leftVar],
borderColor: '#b5179e',
backgroundColor: '#b5179e',
borderWidth: 1.5,
pointRadius: 2,
tension: 0,
spanGaps: true,
});
datasets.push({
label: `${vr.label} (${vr.unit})`,
data: seriesData[rightVar],
borderColor: '#0077b6',
backgroundColor: '#0077b6',
borderWidth: 1.5,
pointRadius: 2,
tension: 0,
spanGaps: true,
});
}
// Add marker points for selected years
const leftIdx = leftYear - minYear;
const rightIdx = rightYear - minYear;
const markerData = sameVar ? seriesData[leftVar] : seriesData[leftVar];
const leftMarkerVal = markerData[leftIdx];
const rightMarkerVal = sameVar ? markerData[rightIdx] : seriesData[rightVar][rightIdx];
const markerLeft = new Array(years.length).fill(null);
if (leftMarkerVal !== null) markerLeft[leftIdx] = leftMarkerVal;
datasets.push({
label: 'Left year',
data: markerLeft,
borderColor: '#b5179e',
backgroundColor: '#b5179e',
pointRadius: 5,
pointStyle: 'circle',
showLine: false,
});
const markerRight = new Array(years.length).fill(null);
if (rightMarkerVal !== null) markerRight[rightIdx] = rightMarkerVal;
datasets.push({
label: 'Right year',
data: markerRight,
borderColor: '#0077b6',
backgroundColor: '#0077b6',
pointRadius: 5,
pointStyle: 'circle',
showLine: false,
});
pointChart = new Chart(canvas, {
type: 'line',
data: { labels: years, datasets },
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
display: !sameVar,
labels: { boxWidth: 10, font: { size: 10 }, filter: (item) => !item.text.includes('year') },
},
tooltip: {
callbacks: {
label: (ctx) => `${ctx.dataset.label}: ${ctx.parsed.y !== null ? ctx.parsed.y.toFixed(1) : 'No data'}`,
},
},
},
scales: {
x: {
ticks: { font: { size: 9 }, maxTicksLimit: 6 },
grid: { display: false },
},
y: {
beginAtZero: true,
ticks: { font: { size: 9 }, maxTicksLimit: 5 },
grid: { color: '#eee' },
},
},
interaction: { mode: 'nearest', intersect: true },
animation: { duration: 0 },
},
});
} catch (err) {
popup.setContent('<span class="point-loading">Error fetching values</span>');
}
});
// Left controls
document.getElementById('var-left').addEventListener('change', (e) => {
leftVar = e.target.value;
updateLayers();
});
document.getElementById('slider-left').addEventListener('input', (e) => {
leftYear = parseInt(e.target.value);
updateLayers();
});
// Right controls
document.getElementById('var-right').addEventListener('change', (e) => {
rightVar = e.target.value;
updateLayers();
});
document.getElementById('slider-right').addEventListener('input', (e) => {
rightYear = parseInt(e.target.value);
updateLayers();
});
// Opacity control
document.getElementById('opacity-slider').addEventListener('input', (e) => {
layerOpacity = parseInt(e.target.value) / 100;
document.getElementById('opacity-val').textContent = e.target.value + '%';
if (leftLayer) leftLayer.setOpacity(layerOpacity);
if (rightLayer) rightLayer.setOpacity(layerOpacity);
updateHash();
});
// Keyboard shortcuts
document.addEventListener('keydown', (e) => {
if (e.target.tagName === 'SELECT') return;
if (e.shiftKey) {
if (e.key === 'ArrowLeft' && rightYear > 1990) {
rightYear--;
document.getElementById('slider-right').value = rightYear;
updateLayers();
}
if (e.key === 'ArrowRight' && rightYear < 2023) {
rightYear++;
document.getElementById('slider-right').value = rightYear;
updateLayers();
}
} else {
if (e.key === 'ArrowLeft' && leftYear > 1990) {
leftYear--;
document.getElementById('slider-left').value = leftYear;
updateLayers();
}
if (e.key === 'ArrowRight' && leftYear < 2023) {
leftYear++;
document.getElementById('slider-left').value = leftYear;
updateLayers();
}
}
});
updateLayers();
</script>
</body>
</html>