Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
2630 lines (2408 loc) · 106 KB
/
Copy pathapp.js
File metadata and controls
2630 lines (2408 loc) · 106 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
/* Disaster Imagery Viewer
*
* Answers three questions for an active humanitarian mapping response:
* 1. What imagery exists over this area, and how old is it?
* 2. What are Tasking Manager mappers actually looking at right now?
* 3. How does the ground compare before and after the event?
*
* Imagery streams live from provider tile endpoints. The catalogue is baked by
* scripts/build_catalog.py because the OpenAerialMap API restricts CORS to
* map.openaerialmap.org and the Tasking Manager API sends no CORS header.
* Tasking Manager state is refreshed live in the browser from the insta-tm
* mirror, which does send CORS headers.
*/
'use strict';
const INSTA_TM = 'https://pub-9f93f222eb8648a08829b4d1cd8edcfb.r2.dev';
const OVERPASS = 'https://overpass-api.de/api/interpreter';
const DEFAULT_EVENT = 'nepal-floods-2026';
// Event pages are served from /<event-id>/, one level below the app assets, and
// declare window.APP_BASE so fetches still resolve.
const BASE = window.APP_BASE || '';
// Task states, in the order a task moves through them.
const TASK_COLORS = {
READY: '#3b4655',
LOCKED_FOR_MAPPING: '#c8a3ff',
MAPPED: '#4d9de0',
LOCKED_FOR_VALIDATION: '#c8a3ff',
VALIDATED: '#5ec26a',
INVALIDATED: '#f0883e',
BADIMAGERY: '#d73f3f',
SPLIT: '#697687',
ARCHIVED: '#697687'
};
const TASK_LABELS = {
READY: 'Available', MAPPED: 'Mapped', VALIDATED: 'Validated',
BADIMAGERY: 'Bad imagery', INVALIDATED: 'Needs rework',
LOCKED_FOR_MAPPING: 'Being mapped', LOCKED_FOR_VALIDATION: 'Being validated',
SPLIT: 'Split', ARCHIVED: 'Archived'
};
// Distinct outline colour per Tasking Manager project.
const PROJECT_COLORS = ['#d73f3f', '#f0c94d', '#00b8a9', '#ff7ab8', '#8bd450'];
// OSM overlay styling. Buildings and roads must not look the same.
const OSM_NEW = '#ffd24d'; // edited since the event
const OSM_BUILDING = '#4d9de0';
const OSM_ROAD = '#5ec26a';
// Age bands for Esri basemap capture dates. The point is to make it obvious at
// a glance where a mapper is tracing something years out of date.
const SEAMLINE_BANDS = [
{ from: 2025, color: '#5ec26a', label: '2025 or newer' },
{ from: 2022, color: '#4d9de0', label: '2022-2024' },
{ from: 2019, color: '#f0c94d', label: '2019-2021' },
{ from: 2016, color: '#f0883e', label: '2016-2018' },
{ from: 0, color: '#d73f3f', label: 'before 2016' }
];
const BASEMAPS = [
{ id: 'esri', name: 'Esri World Imagery', note: 'Default in most OSM editors',
tiles: ['https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}'],
attribution: 'Esri, Maxar, Earthstar Geographics', maxzoom: 19 },
// Bing serves tiles by quadkey, which MapLibre cannot template. We point the
// source at a sentinel URL and rewrite it to the real quadkey in
// transformRequest below.
{ id: 'bing', name: 'Bing Aerial', note: 'Often older than Esri in mountain terrain',
tiles: ['https://bing.tiles.invalid/{z}/{x}/{y}'],
attribution: 'Microsoft Bing Maps', maxzoom: 19 },
{ id: 'osm', name: 'OSM Standard', note: 'Shows what has been mapped',
tiles: ['https://tile.openstreetmap.org/{z}/{x}/{y}.png'],
attribution: 'OpenStreetMap contributors', maxzoom: 19 },
{ id: 'none', name: 'None (dark)', note: '', tiles: null }
];
const GROUPS = [
{ id: 'post-satellite', name: 'Post-event satellite', color: '#f0883e', open: true },
{ id: 'post-drone', name: 'Post-event drone', color: '#f0883e', open: true },
{ id: 'pre-drone', name: 'Pre-event drone', color: '#5ec26a', open: true },
{ id: 'pre-satellite', name: 'Pre-event satellite', color: '#4d9de0', open: true },
{ id: 'archive', name: 'Older archive', color: '#8b7cc8', open: false }
];
const state = {
cfg: null, catalog: null,
scenes: [], sceneById: new Map(),
active: [], // [{key, name, kind, source, opacity, side}]
basemap: 'esri',
compare: false, splitPct: 50,
mapA: null, mapB: null, syncing: false,
vectorsOn: new Set(),
collapsed: new Set(['phase:archive']),
groupBy: 'phase', sortBy: 'date-desc',
providersOn: new Set(), // selected providers; empty means no provider filter
activeOnly: false,
taskGrid: null, // { projectId: [geometry, ...] }
showTaskGrid: false,
tmOn: new Set(), // project ids currently drawn
gridProject: null, // task grid is shown for one project at a time
osmAoi: null, // AOI-wide OSM snapshot, loaded in the background
osmStats: null,
showAoiOsm: false,
optical: [],
sarMode: 'db',
opticalMode: 'tci',
renderChoice: {}, // sceneId -> render id, for multi-rendering scenes
sar: [], // Sentinel-1 scenes from the Planetary Computer
osmFresh: null
};
const $ = (s) => document.querySelector(s);
const el = (t, c, h) => { const n = document.createElement(t); if (c) n.className = c; if (h !== undefined) n.innerHTML = h; return n; };
const esc = (s) => String(s == null ? '' : s).replace(/[&<>"']/g, (m) =>
({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[m]));
/* ------------------------------------------------------------------ utils */
/* Always render in UTC. Capture dates must read the same for someone in
* Kathmandu and someone in California, and a bare YYYY-MM-DD parsed by Date()
* is UTC midnight, which slips to the previous day west of Greenwich. */
const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
function fmtDate(iso) {
if (!iso) return 'date unknown';
const d = new Date(iso);
if (isNaN(d)) return String(iso).slice(0, 10);
return `${String(d.getUTCDate()).padStart(2, '0')} ${MONTHS[d.getUTCMonth()]} ${d.getUTCFullYear()}`;
}
/* Some scenes ship several renderings of the same capture (natural colour, NIR
* false colour, NDWI). They are one catalogue row with a selector rather than a
* row each, which would triple the list. */
function sceneRenders(scene) {
return Array.isArray(scene.renders) && scene.renders.length ? scene.renders : null;
}
function activeRender(scene) {
const rs = sceneRenders(scene);
if (!rs) return null;
return rs.find((r) => r.id === state.renderChoice[scene.id]) || rs[0];
}
function sceneTileUrl(scene) {
const r = activeRender(scene);
return (r && r.tile_url) || scene.tile_url || scene.tms;
}
/* Key and label for a scene in a given rendering. Both must agree, or the
* active-layer list and the compare dropdowns end up out of step. */
function sceneKey(scene) {
const rs = sceneRenders(scene);
const r = activeRender(scene);
return 's:' + scene.id + (rs && rs.length > 1 && r ? ':' + r.id : '');
}
function sceneLabel(scene) {
const rs = sceneRenders(scene);
const r = activeRender(scene);
return rs && rs.length > 1 && r ? `${scene.title} ${r.name}` : scene.title;
}
function fmtGsd(cm) {
if (cm == null) return null;
return cm >= 100 ? `${(cm / 100).toFixed(cm >= 1000 ? 0 : 1)} m` : `${cm.toFixed(0)} cm`;
}
/* Relative timestamps are rendered once, so refresh them on a timer. A viewer
* left open through a response would otherwise still claim the catalogue was
* built "3 min ago" hours later. */
/* How old the catalogue may get before the viewer says so loudly. CI is meant
* to refresh hourly; three hours means something is wrong, and during a response
* a quietly stale page is more dangerous than an obviously broken one. */
const STALE_AFTER_MIN = 180;
function renderHealth() {
const box = $('#health');
if (!box) return;
const cat = state.catalog || {};
const notes = [];
const mins = cat.generated
? Math.round((Date.now() - new Date(cat.generated).getTime()) / 60000) : null;
if (mins != null && mins > STALE_AFTER_MIN) {
const h = Math.floor(mins / 60);
notes.push(`The imagery catalogue was last rebuilt <b>${h} hours ago</b> and should refresh hourly. Newly released imagery may be missing.`);
}
const stale = Object.entries(cat.sources || {})
.filter(([, v]) => v.status === 'stale').map(([k]) => k);
if (stale.length) {
notes.push(`Showing previously saved data for: <b>${stale.map(esc).join(', ')}</b>.`);
}
if ((cat.failures || []).length) {
// Failures are tagged objects; older catalogues used plain strings.
const fmt = (f) => typeof f === 'string' ? f
: `${f.what || f.source || 'source'}${f.detail ? ' (' + f.detail + ')' : ''}`;
const list = cat.failures.slice(0, 3).map((f) => esc(fmt(f))).join('; ');
const more = cat.failures.length > 3 ? ` and ${cat.failures.length - 3} more` : '';
notes.push(`${cat.failures.length} upstream source${cat.failures.length > 1 ? 's' : ''} failed on the last build: ${list}${more}.`);
}
box.hidden = notes.length === 0;
box.innerHTML = notes.map((n) => `<p>${n}</p>`).join('');
}
function startAgoTicker() {
const tick = () => {
const cat = state.catalog && state.catalog.generated;
if (cat) {
const f = $('#freshness');
if (f) f.textContent = `Event ${fmtDate(state.cfg.eventDate)} \u00b7 catalogue ${ago(cat)}`;
}
renderHealth();
document.querySelectorAll('.js-ago').forEach((el2) => {
const iso = el2.dataset.iso;
if (iso) el2.textContent = ago(iso);
});
if (state.osmFresh) {
const o = $('#osm-fresh');
if (o) o.textContent = 'OSM snapshot ' + ago(state.osmFresh.replace(' ', 'T'));
}
};
setInterval(tick, 30000);
}
function ago(iso) {
if (!iso) return '';
const mins = Math.round((Date.now() - new Date(iso).getTime()) / 60000);
if (isNaN(mins)) return '';
if (mins < 2) return 'just now';
if (mins < 60) return `${mins} min ago`;
const h = Math.round(mins / 60);
if (h < 36) return `${h} h ago`;
return `${Math.round(h / 24)} d ago`;
}
function tileToQuadkey(x, y, z) {
let qk = '';
for (let i = z; i > 0; i--) {
let digit = 0;
const mask = 1 << (i - 1);
if ((x & mask) !== 0) digit += 1;
if ((y & mask) !== 0) digit += 2;
qk += digit;
}
return qk;
}
/* ------------------------------------------------------------------- maps */
function baseStyle() {
return {
version: 8,
glyphs: 'https://demotiles.maplibre.org/font/{fontstack}/{range}.pbf',
sources: {}, layers: [{ id: 'bg', type: 'background', paint: { 'background-color': '#0a0d11' } }]
};
}
let pmtilesRegistered = false;
function ensurePmtiles() {
if (pmtilesRegistered || typeof pmtiles === 'undefined') return;
maplibregl.addProtocol('pmtiles', new pmtiles.Protocol().tile);
pmtilesRegistered = true;
}
function makeMap(container) {
ensurePmtiles();
const m = new maplibregl.Map({
container,
style: baseStyle(),
center: state.cfg.center || [0, 0],
zoom: state.cfg.zoom || 10,
maxZoom: 22,
attributionControl: false,
transformRequest: (url) => {
const bing = url.match(/^https:\/\/bing\.tiles\.invalid\/(\d+)\/(\d+)\/(\d+)/);
if (bing) {
const z = +bing[1], x = +bing[2], y = +bing[3];
const qk = tileToQuadkey(x, y, z);
const server = x % 4;
return { url: `https://ecn.t${server}.tiles.virtualearth.net/tiles/a${qk}.jpeg?g=1` };
}
return { url };
}
});
m.addControl(new maplibregl.NavigationControl({ visualizePitch: false }), 'top-left');
m.addControl(new maplibregl.ScaleControl({ maxWidth: 110, unit: 'metric' }), 'bottom-right');
m.addControl(new maplibregl.AttributionControl({ compact: true }), 'bottom-right');
return m;
}
function eachMap(fn) {
if (state.mapA) fn(state.mapA, 'A');
if (state.mapB && state.compare) fn(state.mapB, 'B');
}
/* Apply the current layer stack to one map instance. Rebuilt wholesale on
* change: the stacks are small (a handful of raster layers) and this avoids a
* class of ordering bugs that are painful to debug during a live response. */
function renderMap(map, which) {
if (!map) return;
// Adding a source briefly puts the style back into a loading state. If a
// second layer is toggled during that window a plain early return would drop
// it silently, so keep the latest requested render and retry until the style
// settles. The "idle" event is not reliable here because tile loading can
// keep the map busy indefinitely.
if (!map.isStyleLoaded()) {
map._pendingRender = which;
if (!map._pendingTimer) {
map._pendingTimer = setInterval(() => {
if (!map.isStyleLoaded()) return;
clearInterval(map._pendingTimer);
map._pendingTimer = null;
const w = map._pendingRender;
map._pendingRender = null;
if (w) renderMap(map, w);
}, 120);
}
return;
}
if (map._pendingTimer) { clearInterval(map._pendingTimer); map._pendingTimer = null; }
map._pendingRender = null;
// Remove everything we added previously.
const style = map.getStyle();
for (const layer of style.layers.slice().reverse()) {
if (layer.id !== 'bg') map.removeLayer(layer.id);
}
for (const id of Object.keys(style.sources || {})) map.removeSource(id);
// Basemap.
const bm = BASEMAPS.find((b) => b.id === state.basemap);
if (bm && bm.tiles) {
map.addSource('basemap', {
type: 'raster', tiles: bm.tiles, tileSize: 256,
maxzoom: bm.maxzoom || 19, attribution: bm.attribution
});
map.addLayer({ id: 'basemap', type: 'raster', source: 'basemap' });
}
// Imagery stack, bottom to top. In compare mode each map shows only its side.
const stack = state.compare
? state.active.filter((a) => a.side === (which === 'A' ? 'left' : 'right'))
: state.active;
stack.slice().reverse().forEach((a, i) => {
const sid = `img-${i}`;
const src = {
type: 'raster', tiles: [a.url], tileSize: 256,
minzoom: a.minzoom || 0, maxzoom: a.maxzoom || 22,
attribution: a.attribution || ''
};
// Constrain requests to the scene footprint. Without this MapLibre asks for
// the whole viewport grid and titiler 404s everything outside the image,
// which was 60-odd wasted requests against a shared HOT service per pan.
if (a.bounds) src.bounds = a.bounds;
map.addSource(sid, src);
map.addLayer({
id: sid, type: 'raster', source: sid,
paint: { 'raster-opacity': a.opacity, 'raster-fade-duration': 120 }
});
});
// Vector overlays sit above imagery.
addVectors(map);
}
function renderAll() { eachMap(renderMap); }
/* --------------------------------------------------------------- vectors */
function addVectors(map) {
const cat = state.catalog;
// Task grid. The projects share an identical AOI, so grids are drawn for one
// project at a time; stacking them is unreadable.
if (state.showTaskGrid && state.taskGrid && state.gridProject) {
const p = cat.tm_projects.find((x) => x.id === state.gridProject);
const geoms = p && state.taskGrid[String(p.id)];
const statuses = p && p.task_status;
if (geoms && statuses) {
// Joined by task id, so a reordered grid cannot mislabel statuses.
const feats = Object.entries(geoms).map(([tid, g]) => ({
type: 'Feature', geometry: g,
properties: { s: statuses[tid] || 'READY', tid }
}));
map.addSource('tasks', { type: 'geojson', data: { type: 'FeatureCollection', features: feats } });
const colorExpr = ['match', ['get', 's']];
for (const [k, v] of Object.entries(TASK_COLORS)) colorExpr.push(k, v);
colorExpr.push('#3b4655');
map.addLayer({
id: 'tasks-fill', type: 'fill', source: 'tasks',
paint: {
'fill-color': colorExpr,
'fill-opacity': ['match', ['get', 's'], 'READY', 0.14, 0.4]
}
});
map.addLayer({
id: 'tasks-line', type: 'line', source: 'tasks',
paint: { 'line-color': colorExpr, 'line-width': 0.6, 'line-opacity': 0.5 }
});
}
}
// Tasking Manager project extents. Each project toggles independently and
// gets its own colour, because their boundaries overlap almost exactly.
const shown = cat.tm_projects.filter((p) => p.aoi && state.tmOn.has(p.id));
if (shown.length) {
// Offset the line width slightly per project so coincident boundaries
// remain distinguishable rather than painting over one another.
shown.forEach((p, idx) => {
const i = cat.tm_projects.indexOf(p);
const color = PROJECT_COLORS[i % PROJECT_COLORS.length];
const sid = `tm-${p.id}`;
map.addSource(sid, {
type: 'geojson',
data: { type: 'Feature', geometry: p.aoi, properties: { id: p.id } }
});
map.addLayer({
id: sid + '-fill', type: 'fill', source: sid,
paint: { 'fill-color': color, 'fill-opacity': state.showTaskGrid ? 0.02 : 0.05 }
});
map.addLayer({
id: sid + '-line', type: 'line', source: sid,
paint: {
'line-color': color,
'line-width': 2.5,
'line-opacity': 0.95,
'line-offset': idx * 3
}
});
});
}
// Config-driven vector layers (UNOSAT extent, and similar).
for (const layer of (state.cfg.extraLayers || [])) {
if (!state.vectorsOn.has(layer.id)) continue;
if (layer.type === 'geojson') {
const data = state._geojson && state._geojson[layer.id];
if (!data) continue;
map.addSource(layer.id, { type: 'geojson', data, attribution: layer.attribution || '' });
/* One source can carry polygons, lines and points at once (the UNOSAT and
* SERTIT services do), so filter each draw layer by geometry type rather
* than assuming polygons. `geometry-type` reports Polygon for MultiPolygon
* and LineString for MultiLineString.
*/
const color = layerColor(layer);
const isPoly = ['==', ['geometry-type'], 'Polygon'];
const isLine = ['==', ['geometry-type'], 'LineString'];
const isPoint = ['==', ['geometry-type'], 'Point'];
if (layer.fill !== false) {
map.addLayer({ id: layer.id + '-fill', type: 'fill', source: layer.id, filter: isPoly,
paint: {
'fill-color': color,
'fill-opacity': layer.fillOpacity != null ? layer.fillOpacity : 0.25
} });
}
map.addLayer({ id: layer.id + '-line', type: 'line', source: layer.id,
filter: ['any', isPoly, isLine],
paint: {
'line-color': color,
'line-width': layer.lineWidth || 1.6,
'line-opacity': 0.95
} });
map.addLayer({ id: layer.id + '-point', type: 'circle', source: layer.id, filter: isPoint,
paint: {
'circle-color': color,
'circle-radius': ['interpolate', ['linear'], ['zoom'], 9, 3, 14, 6, 17, 9],
'circle-stroke-width': 1,
'circle-stroke-color': 'rgba(0,0,0,0.75)',
'circle-opacity': 0.9
} });
} else if (layer.type === 'pmtiles') {
map.addSource(layer.id, {
type: 'vector', url: 'pmtiles://' + layer.url,
attribution: layer.attribution || ''
});
map.addLayer({
id: layer.id + '-fill', type: 'fill', source: layer.id,
'source-layer': layer.sourceLayer,
minzoom: layer.minzoom || 0,
paint: {
'fill-color': layer.color || '#c8a3ff',
'fill-opacity': layer.opacity != null ? layer.opacity : 0.5,
'fill-outline-color': '#ffffff'
}
});
map.addLayer({
id: layer.id + '-line', type: 'line', source: layer.id,
'source-layer': layer.sourceLayer,
minzoom: layer.minzoom || 0,
paint: { 'line-color': layer.color || '#c8a3ff', 'line-width': 1.1, 'line-opacity': 0.9 }
});
}
}
// Esri basemap capture dates, drawn under everything else.
if (state.vectorsOn.has('esri-seamlines') && state._seamlines) {
map.addSource('seamlines', { type: 'geojson', data: state._seamlines });
const colorExpr = ['step', ['coalesce', ['get', 'year'], 0]];
const asc = SEAMLINE_BANDS.slice().reverse();
colorExpr.push(asc[0].color);
for (const b of asc.slice(1)) colorExpr.push(b.from, b.color);
map.addLayer({
id: 'seamlines-fill', type: 'fill', source: 'seamlines',
paint: { 'fill-color': colorExpr, 'fill-opacity': 0.22 }
});
map.addLayer({
id: 'seamlines-line', type: 'line', source: 'seamlines',
paint: { 'line-color': colorExpr, 'line-width': 1.2, 'line-opacity': 0.9 }
});
}
// Live OpenStreetMap. Buildings and roads are styled distinctly, and anything
// edited since the event is highlighted so mapping progress is visible.
const osmData = state._osm || (state.showAoiOsm ? state.osmAoi : null);
if (osmData) {
map.addSource('osm-live', { type: 'geojson', data: osmData });
map.addLayer({
id: 'osm-bldg-fill', type: 'fill', source: 'osm-live',
filter: ['all', ['==', ['geometry-type'], 'Polygon'], ['==', ['get', '_kind'], 'building']],
paint: {
'fill-color': ['case', ['==', ['get', '_new'], 1], OSM_NEW, OSM_BUILDING],
'fill-opacity': 0.4
}
});
map.addLayer({
id: 'osm-bldg-line', type: 'line', source: 'osm-live',
filter: ['all', ['==', ['geometry-type'], 'Polygon'], ['==', ['get', '_kind'], 'building']],
paint: {
'line-color': ['case', ['==', ['get', '_new'], 1], OSM_NEW, OSM_BUILDING],
'line-width': 1
}
});
// Roads: casing plus a coloured core, width scaled by class and zoom.
// A zoom expression has to be the top-level interpolate, so the casing gets
// its own set of stops rather than arithmetic wrapped around the core width.
const roadFilter = ['==', ['get', '_kind'], 'road'];
const widthStops = (bump) => [
'interpolate', ['linear'], ['zoom'],
12, ['match', ['get', '_class'], 'major', 2.2 + bump, 'minor', 1.2 + bump, 0.8 + bump],
18, ['match', ['get', '_class'], 'major', 9 + bump, 'minor', 5 + bump, 3 + bump]
];
map.addLayer({
id: 'osm-road-case', type: 'line', source: 'osm-live', filter: roadFilter,
layout: { 'line-cap': 'round', 'line-join': 'round' },
paint: { 'line-color': '#0e1116', 'line-width': widthStops(2), 'line-opacity': 0.75 }
});
// line-dasharray cannot be data-driven, so tracks get their own layer.
map.addLayer({
id: 'osm-road', type: 'line', source: 'osm-live',
filter: ['all', roadFilter, ['!=', ['get', '_class'], 'track']],
layout: { 'line-cap': 'round', 'line-join': 'round' },
paint: {
'line-color': ['case', ['==', ['get', '_new'], 1], OSM_NEW, OSM_ROAD],
'line-width': widthStops(0)
}
});
map.addLayer({
id: 'osm-track', type: 'line', source: 'osm-live',
filter: ['all', roadFilter, ['==', ['get', '_class'], 'track']],
layout: { 'line-cap': 'butt', 'line-join': 'round' },
paint: {
'line-color': ['case', ['==', ['get', '_new'], 1], OSM_NEW, OSM_ROAD],
'line-width': widthStops(0),
'line-dasharray': [2, 1.5]
}
});
}
if (state._hover) {
map.addSource('hover', { type: 'geojson', data: state._hover });
map.addLayer({
id: 'hover-line', type: 'line', source: 'hover',
paint: { 'line-color': '#ffffff', 'line-width': 2, 'line-dasharray': [2, 2] }
});
}
}
/* Campaign project names share a long boilerplate prefix, and often a long
* shared tail as well, leaving a few words that actually distinguish them.
* Those shared parts are derived from the names present rather than hardcoded,
* so this works for any event and cannot strip one project's identity while
* leaving another's. Hardcoding was the previous approach and it removed
* "Upper Trishuli and Bhote Koshi Corridor" but not "Lower", hiding the very
* distinction that mattered, and reduced two projects to the word "project".
*/
function commonEdges() {
if (state._nameEdges) return state._nameEdges;
const names = (state.catalog.tm_projects || [])
.map((p) => String(p.name || '').trim()).filter(Boolean);
// Do not cache an answer derived from nothing: a later render would keep it.
if (!names.length) return { prefix: '', suffix: '' };
const words = (str) => str.split(/\s+/).filter(Boolean);
const toBoundary = (str) => str.replace(/[^\s\-\u2013:]*$/, '');
let prefix = '';
if (names.length > 1) {
prefix = names[0];
for (const n of names.slice(1)) {
let i = 0;
while (i < prefix.length && i < n.length && prefix[i] === n[i]) i++;
prefix = prefix.slice(0, i);
}
prefix = toBoundary(prefix);
}
/* Shared tail of the remainders, compared by whole words. Comparing by
* character can cut inside a word, turning "Bhotekoshi" into "Bhote" when
* another project ends in "koshi". Never consume an entire area either, or a
* project whose name is exactly the shared tail would lose its identity while
* its neighbours kept theirs.
*/
const areas = names.map((n) => (n.startsWith(prefix) ? n.slice(prefix.length) : n)
.replace(/\[[^\]]*\]/g, '').trim()).filter(Boolean);
let suffixWords = [];
if (areas.length > 1) {
const lists = areas.map(words);
const shortest = Math.min(...lists.map((l) => l.length));
let k = 0;
while (k < shortest &&
lists.every((l) => l[l.length - 1 - k] === lists[0][lists[0].length - 1 - k])) k++;
k = Math.min(k, Math.max(0, shortest - 1));
if (k) suffixWords = lists[0].slice(lists[0].length - k);
}
state._nameEdges = { prefix, suffix: suffixWords.join(' '), suffixWords };
return state._nameEdges;
}
function shortProjectName(name) {
const raw = String(name || '').trim();
const { prefix, suffixWords } = commonEdges();
let rest = (prefix && raw.startsWith(prefix)) ? raw.slice(prefix.length) : raw;
const theme = (rest.match(/\[([^\]]+)\]/) || [])[1] || '';
let aw = rest.replace(/\[[^\]]*\]/g, '').trim().split(/\s+/).filter(Boolean);
const sw = suffixWords || [];
if (sw.length && aw.length > sw.length &&
sw.every((w, i) => aw[aw.length - sw.length + i] === w)) {
aw = aw.slice(0, aw.length - sw.length);
}
const area = aw.join(' ').replace(/[\s\-\u2013,]+$/, '');
const parts = [area, theme].filter(Boolean);
return parts.length ? parts.join(' \u00b7 ') : (raw || 'project');
}
/* --------------------------------------------------------------- compare */
function syncMaps(from, to) {
if (state.syncing) return;
state.syncing = true;
to.jumpTo({
center: from.getCenter(), zoom: from.getZoom(),
bearing: from.getBearing(), pitch: from.getPitch()
});
state.syncing = false;
}
function setSplit(pct) {
state.splitPct = Math.max(2, Math.min(98, pct));
const wrap = $('#mapwrap');
const w = wrap.clientWidth;
const x = (state.splitPct / 100) * w;
$('#map-b').style.clipPath = `inset(0 0 0 ${state.splitPct}%)`;
$('#swipe-handle').style.left = `${x}px`;
}
function enableCompare(on) {
state.compare = on;
$('#compare-controls').hidden = !on;
$('#swipe-handle').hidden = !on;
$('#map-b').hidden = !on;
if (on) {
if (!state.mapB) {
state.mapB = makeMap('map-b');
state.mapB.on('load', () => {
// Adopt map A's current view, otherwise the second map opens at the
// event's default position rather than wherever the user is looking.
syncMaps(state.mapA, state.mapB);
renderMap(state.mapB, 'B');
setSplit(state.splitPct);
});
state.mapA.on('move', () => syncMaps(state.mapA, state.mapB));
state.mapB.on('move', () => syncMaps(state.mapB, state.mapA));
} else {
state.mapB.resize();
syncMaps(state.mapA, state.mapB);
}
// Every layer is created on the right, so a "does anything sit on the right"
// test never fires and the left pane would open blank. Split the stack
// instead: newest on the right, next one on the left.
if (state.active.length && !state.active.some((a) => a.side === 'left')) {
if (state.active.length === 1) {
state.active[0].side = 'right';
} else {
state.active.forEach((a, i) => { a.side = i === 0 ? 'right' : 'left'; });
}
}
setSplit(state.splitPct);
}
renderAll();
renderActive();
}
function initSwipeDrag() {
const handle = $('#swipe-handle');
let dragging = false;
const move = (e) => {
if (!dragging) return;
const rect = $('#mapwrap').getBoundingClientRect();
const cx = (e.touches ? e.touches[0].clientX : e.clientX) - rect.left;
setSplit((cx / rect.width) * 100);
e.preventDefault();
};
const stop = () => { dragging = false; document.body.style.cursor = ''; };
handle.addEventListener('mousedown', (e) => { dragging = true; document.body.style.cursor = 'ew-resize'; e.preventDefault(); });
handle.addEventListener('touchstart', (e) => { dragging = true; e.preventDefault(); }, { passive: false });
window.addEventListener('mousemove', move);
window.addEventListener('touchmove', move, { passive: false });
window.addEventListener('mouseup', stop);
window.addEventListener('touchend', stop);
}
/* ------------------------------------------------------------ layer stack */
function toggleScene(scene) {
const key = sceneKey(scene);
const i = state.active.findIndex((a) => a.key === key);
if (i >= 0) {
state.active.splice(i, 1);
} else {
state.active.unshift({
key,
name: sceneLabel(scene),
kind: 'scene', scene,
url: sceneTileUrl(scene).replace(/\{-y\}/g, '{y}'),
opacity: 1, side: 'right',
attribution: scene.attribution || `${scene.provider} via OpenAerialMap`,
bounds: (scene.bbox && scene.bbox.length === 4) ? scene.bbox : null,
maxzoom: 22
});
}
renderActive(); renderCatalog(); renderAll(); writeHash();
}
function toggleExtraRaster(layer) {
const key = 'x:' + layer.id;
const i = state.active.findIndex((a) => a.key === key);
if (i >= 0) state.active.splice(i, 1);
else state.active.unshift({
key, name: layer.name, kind: 'extra', layer,
url: layer.url, opacity: 1, side: 'right',
attribution: layer.attribution || '', maxzoom: layer.maxzoom || 18
});
renderActive(); renderMosaics(); renderAll(); writeHash();
}
function isActive(key) { return state.active.some((a) => a.key === key); }
/* ------------------------------------------------------------------- UI */
function renderActive() {
const block = $('#active-block');
const list = $('#active-list');
block.hidden = state.active.length === 0;
const n = $('#active-count');
if (n) n.textContent = state.active.length ? String(state.active.length) : '';
list.innerHTML = '';
state.active.forEach((a, idx) => {
const item = el('div', 'active-item');
const row = el('div', 'row1');
row.appendChild(el('span', 'nm', esc(a.name)));
if (idx > 0) {
const up = el('button', 'iconbtn', '▲');
up.title = 'Move up';
up.onclick = () => { const t = state.active[idx - 1]; state.active[idx - 1] = state.active[idx]; state.active[idx] = t; renderActive(); renderAll(); };
row.appendChild(up);
}
if (idx < state.active.length - 1) {
const dn = el('button', 'iconbtn', '▼');
dn.title = 'Move down';
dn.onclick = () => { const t = state.active[idx + 1]; state.active[idx + 1] = state.active[idx]; state.active[idx] = t; renderActive(); renderAll(); };
row.appendChild(dn);
}
const rm = el('button', 'iconbtn rm', '✕');
rm.title = 'Remove';
rm.onclick = () => { state.active.splice(idx, 1); renderActive(); renderCatalog(); renderMosaics(); renderAll(); writeHash(); };
row.appendChild(rm);
item.appendChild(row);
const orow = el('div', 'opacity-row');
const rng = el('input');
rng.type = 'range'; rng.min = 0; rng.max = 100; rng.value = Math.round(a.opacity * 100);
const pct = el('span', 'pct', `${Math.round(a.opacity * 100)}%`);
rng.oninput = () => {
a.opacity = rng.value / 100;
pct.textContent = `${rng.value}%`;
eachMap((m) => {
const stack = state.compare ? state.active.filter((x) => x.side === a.side) : state.active;
const pos = stack.indexOf(a);
if (pos < 0) return;
const lid = `img-${stack.length - 1 - pos}`;
if (m.getLayer(lid)) m.setPaintProperty(lid, 'raster-opacity', a.opacity);
});
};
orow.appendChild(rng); orow.appendChild(pct);
item.appendChild(orow);
list.appendChild(item);
});
// Compare side selectors.
for (const side of ['left', 'right']) {
const sel = $(`#cmp-${side}`);
sel.innerHTML = '';
state.active.forEach((a) => {
const o = el('option'); o.value = a.key; o.textContent = a.name; sel.appendChild(o);
});
const cur = state.active.find((a) => a.side === side);
if (cur) sel.value = cur.key;
sel.onchange = () => {
const chosen = state.active.find((a) => a.key === sel.value);
if (!chosen) return;
chosen.side = side;
renderAll();
};
}
}
/* Grouping and sorting for the imagery catalogue.
*
* Every option here is a plain property of the scene: when it was taken, how
* coarse it is, who published it. None of them rank scenes by suitability. A
* scene's usefulness depends on where the reader is looking and what they need
* to see, which is not something this catalogue knows.
*/
const GSD_BANDS = [
{ id: 'gsd-0', name: 'Under 25 cm', test: (v) => v != null && v < 25 },
{ id: 'gsd-25', name: '25 to 50 cm', test: (v) => v != null && v >= 25 && v < 50 },
{ id: 'gsd-50', name: '50 cm to 1 m', test: (v) => v != null && v >= 50 && v < 100 },
{ id: 'gsd-100', name: '1 m and coarser', test: (v) => v != null && v >= 100 },
{ id: 'gsd-na', name: 'Resolution not stated', test: (v) => v == null }
];
function groupsFor(scenes) {
const mode = state.groupBy;
if (mode === 'phase') {
return GROUPS
.map((g) => ({ id: 'phase:' + g.id, name: g.name, color: g.color,
scenes: scenes.filter((s) => s.group === g.id) }))
.filter((g) => g.scenes.length);
}
if (mode === 'provider') {
const by = new Map();
for (const s of scenes) {
const k = sourceKey(s);
if (!by.has(k)) by.set(k, []);
by.get(k).push(s);
}
return [...by.entries()]
.sort((a, b) => b[1].length - a[1].length || a[0].localeCompare(b[0]))
.map(([name, list]) => ({ id: 'provider:' + name, name, color: '#7f8a99', scenes: list }));
}
if (mode === 'date') {
const by = new Map();
for (const s of scenes) {
const k = (s.acquired || '').slice(0, 10) || 'Date unknown';
if (!by.has(k)) by.set(k, []);
by.get(k).push(s);
}
return [...by.entries()]
.sort((a, b) => b[0].localeCompare(a[0]))
.map(([k, list]) => ({
id: 'date:' + k,
name: k === 'Date unknown' ? k : fmtDate(k),
color: (list[0] && list[0].phase === 'post') ? '#f0883e' : '#4d9de0',
scenes: list
}));
}
return GSD_BANDS
.map((b) => ({ id: b.id, name: b.name, color: '#7f8a99',
scenes: scenes.filter((s) => b.test(s.gsd_cm)) }))
.filter((g) => g.scenes.length);
}
function sortScenes(list) {
const t = (s) => parseUtc(s.acquired) || 0;
const g = (s) => (s.gsd_cm == null ? Infinity : s.gsd_cm);
const c = (s) => (s.cloud_pct == null ? Infinity : s.cloud_pct);
const out = list.slice();
switch (state.sortBy) {
case 'date-asc': out.sort((a, b) => t(a) - t(b)); break;
case 'gsd-asc': out.sort((a, b) => g(a) - g(b) || t(b) - t(a)); break;
case 'gsd-desc': out.sort((a, b) => g(b) - g(a) || t(b) - t(a)); break;
case 'cloud-asc': out.sort((a, b) => c(a) - c(b) || t(b) - t(a)); break;
case 'provider': out.sort((a, b) =>
sourceKey(a).localeCompare(sourceKey(b)) || t(b) - t(a)); break;
default: out.sort((a, b) => t(b) - t(a));
}
return out;
}
/* Scenes surviving every filter except the provider chips. The chips need
* counts computed before they themselves are applied, or a provider would drop
* to zero the moment it was switched off and could never be switched back. */
/* Bucket a scene falls into for the chips and for provider grouping.
*
* Drone captures are bucketed as "Drone" rather than by publisher. Ground teams
* fly under many different names, and a chip per team would fragment the one
* category a reader actually wants to pick out. The builder decides what counts
* as a drone from platform and GSD together, because OAM's platform field is
* unreliable here: one of the two orthos over this corridor is tagged
* "satellite" despite being a 3.5 cm flight. Attribution is not lost, the
* publisher still appears on the scene row.
*
* For everything else the publisher name is used, with trailing dots and
* whitespace stripped: OAM attribution is free text, so the same organisation
* arrives both with and without a full stop and would otherwise occupy two
* chips. No fuzzy matching beyond that, which could merge distinct publishers.
*/
function sourceKey(scene) {
if (String(scene.group || '').includes('drone')) return 'Drone';
return String(scene.provider || 'Unattributed').trim().replace(/[.\s]+$/, '') || 'Unattributed';
}
function scenesBeforeProviderFilter() {
const q = ($('#scene-search').value || '').trim().toLowerCase();
const aoiOnly = $('#aoi-only').checked;
let list = state.scenes;
if (aoiOnly) list = list.filter((s) => s.in_aoi);
if (state.activeOnly) list = list.filter((s) => isActive(sceneKey(s)));
if (q) {
list = list.filter((s) =>
(s.title || '').toLowerCase().includes(q) ||
(s.provider || '').toLowerCase().includes(q) ||
(s.sensor || '').toLowerCase().includes(q) ||
(s.acquired || '').toLowerCase().includes(q));
}
return list;
}
/* Chips select rather than exclude: pressing Planet shows Planet. Selecting
* several widens the selection, and pressing a selected chip again removes it.
* No selection at all means no provider filter, so the catalogue starts whole.
*/
function renderProviderChips(pool) {
const wrap = $('#provider-chips');
if (!wrap) return;
wrap.innerHTML = '';
const counts = new Map();
for (const s of pool) {
const k = sourceKey(s);
counts.set(k, (counts.get(k) || 0) + 1);
}
const names = [...counts.keys()].sort((a, b) =>
counts.get(b) - counts.get(a) || a.localeCompare(b));
const anySelected = state.providersOn.size > 0;
/* A selection already in force must stay on screen even when the narrowed
* pool holds fewer than two providers, otherwise a reader can end up staring
* at "no scenes match" with the filter that caused it invisible and no way to
* undo it. Names absent from the pool are still listed, at count zero, so a
* selection can always be seen and lifted.
*/
if (names.length < 2 && !anySelected) return;
for (const sel of state.providersOn) {
if (!counts.has(sel)) { counts.set(sel, 0); names.push(sel); }
}
for (const name of names) {
const on = state.providersOn.has(name);
const chip = el('button', 'chip' + (on ? ' on' : (anySelected ? ' dim' : '')));
chip.innerHTML = `${esc(name)}<span class="n">${counts.get(name)}</span>`;
chip.title = on ? `Stop showing only ${name}` : `Show only ${name}`;
chip.setAttribute('aria-pressed', on ? 'true' : 'false');
chip.onclick = () => {
if (on) state.providersOn.delete(name); else state.providersOn.add(name);
renderCatalog();
};
wrap.appendChild(chip);
}
if (anySelected) {
const clear = el('button', 'chip clear', 'All providers');
clear.onclick = () => { state.providersOn.clear(); renderCatalog(); };
wrap.appendChild(clear);
}
}