-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.js
More file actions
525 lines (437 loc) · 17.2 KB
/
Copy pathscript.js
File metadata and controls
525 lines (437 loc) · 17.2 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
/* pmtiles and protocol, UMD build*/
const { PMTiles, Protocol } = window.pmtiles;
let map;
let layers = {}; // key -> {sourceId, fillLayerId, lineLayerId, sourceLayerName}
let protocol; // hold new Protocol()
/*detect source layer for pmtiles*/
// cache layer ids per pmtile so only fetch metadata once
const sourceLayerCache = new Map();
async function detectSourceLayer(url) {
if (sourceLayerCache.has(url)) return sourceLayerCache.get(url);
const p = new PMTiles(url);
// share instance with the protocol/renderer cache for performance
if (protocol && typeof protocol.add === 'function') protocol.add(p);
const md = await p.getMetadata().catch(() => null);
const candidate =
md?.vector_layers?.[0]?.id || // tippecanoe layer id
md?.name || // generic name field
'tiles'; // fallback
sourceLayerCache.set(url, candidate);
return candidate;
}
/* pmtiles sources (from config.js) */
const pmTilesSources = window.MA_CONFIG?.pmTilesSources;
/* Country view (from config.js) */
const countryViews = window.MA_CONFIG?.countryViews;
/* landcover sources (from config.js) */
const landcoverSources = window.MA_CONFIG?.landcoverSources;
/* Default Settings (from config.js) */
const DEFAULT_COUNTRY = window.MA_CONFIG?.defaultCountry;
const DEFAULT_YEAR = window.MA_CONFIG?.defaultYear;
/* Maptiler base map */
const maptiler_apiKey= window.MAPTILER_APIKEY;
const maptiler = `https://api.maptiler.com/maps/hybrid/{z}/{x}/{y}.jpg?key=${maptiler_apiKey}`;
/* ===== UI State ===== */
let activeCountry = null; // current selected country for Year panel
let fieldBoundaryVisible = false; // changed to false for Tanzania default
let landcoverVisible = false; // global landcover toggle (for active country)
/* ===== Layer helpers ===== */
function layerKey(country, layerType, year) {
return `${country}-${layerType}-${year}`;
}
async function addLayer(country, layerType, year) {
// resolve URL from pmTilesSources (all countries now use { year: url } format)
const entry = pmTilesSources[country];
const sourceUrl = entry?.[year];
if (!sourceUrl) {
throw new Error(`Missing source URL for ${country} ${year ?? ''}`);
}
const key = layerKey(country, layerType, year);
if (layers[key]) return;
const sourceId = `src-${key}`;
const fillLayerId = `fill-${key}`;
const lineLayerId = `line-${key}`;
try {
if (!map.getSource(sourceId)) {
map.addSource(sourceId, { type: 'vector', url: `pmtiles://${sourceUrl}` });
}
const srcLayer = await detectSourceLayer(sourceUrl);
if (!map.getLayer(fillLayerId)) {
map.addLayer({
id: fillLayerId,
type: 'fill',
source: sourceId,
'source-layer': srcLayer,
paint: { 'fill-color': 'rgba(0,0,0,0)', 'fill-outline-color': 'rgba(0,0,0,0)' },
layout: { visibility: fieldBoundaryVisible ? 'visible' : 'none' }
});
}
if (!map.getLayer(lineLayerId)) {
map.addLayer({
id: lineLayerId,
type: 'line',
source: sourceId,
'source-layer': srcLayer,
paint: { 'line-color': 'lightblue', 'line-width': 1 },
layout: { visibility: fieldBoundaryVisible ? 'visible' : 'none' }
});
}
layers[key] = { sourceId, fillLayerId, lineLayerId, sourceLayerName: srcLayer };
} catch (err) {
console.error(`Error creating ${layerType} layer for ${country} ${year ?? ''}:`, err);
}
}
function removeLayer(country, layerType, year) {
const key = layerKey(country, layerType, year);
const entry = layers[key];
if (!entry) return;
if (map.getLayer(entry.lineLayerId)) map.removeLayer(entry.lineLayerId);
if (map.getLayer(entry.fillLayerId)) map.removeLayer(entry.fillLayerId);
if (map.getSource(entry.sourceId)) map.removeSource(entry.sourceId);
delete layers[key];
}
function setFieldBoundaryVisibility(visible) {
fieldBoundaryVisible = visible;
Object.values(layers).forEach(({ fillLayerId, lineLayerId }) => {
if (map.getLayer(fillLayerId)) map.setLayoutProperty(fillLayerId, 'visibility', visible ? 'visible' : 'none');
if (map.getLayer(lineLayerId)) map.setLayoutProperty(lineLayerId, 'visibility', visible ? 'visible' : 'none');
});
}
// remember the last URL used per country
const landcoverUrlCache = new Map(); // key: country, val: cogUrl
function toggleLandcoverForCountry(country, on, year = null) {
if (!country) return;
const entry = landcoverSources[country];
if (!entry) return;
// If target year not specified, use the latest available year
const availableYears = Object.keys(entry).sort();
const targetYear = year || availableYears[availableYears.length - 1];
const rawUrl = entry[targetYear];
if (!rawUrl) return;
// build a COG styled URL.
const cogUrl = `cog://${rawUrl}`;
const sourceId = `landcover-${country}`;
const layerId = sourceId;
if (on) {
const prev = landcoverUrlCache.get(country);
// only replace when URL changed
if (prev && prev !== cogUrl) {
if (map.getLayer(layerId)) map.removeLayer(layerId);
if (map.getSource(sourceId)) map.removeSource(sourceId);
}
if (!map.getSource(sourceId)) {
map.addSource(sourceId, { type: 'raster', url: cogUrl, tileSize: 256, minzoom: 0,
maxzoom: 15 });
}
if (!map.getLayer(layerId)) {
map.addLayer({ id: layerId, type: 'raster', source: sourceId,
minzoom: 0,
maxzoom: 22,
paint: { 'raster-fade-duration': 0 }
});
}
landcoverUrlCache.set(country, cogUrl);
} else {
if (map.getLayer(layerId)) map.removeLayer(layerId);
if (map.getSource(sourceId)) map.removeSource(sourceId);
landcoverUrlCache.delete(country);
}
}
/* Country add/remove */
async function addCountryBase(country) {
const entry = pmTilesSources[country];
if (!entry) return;
}
function removeCountryAll(country) {
const entry = pmTilesSources[country];
if (!entry) return;
// Remove all year layers for the country
Object.keys(entry).forEach(yr => removeLayer(country, 'pmtiles', yr));
// remove landcover for that country
toggleLandcoverForCountry(country, false);
}
/* ===== Year button ===== */
function listYearsForCountry(country) {
const pmEntry = pmTilesSources?.[country];
const lcEntry = landcoverSources?.[country];
// Combine years from both pmtiles and landcover sources
const yearsSet = new Set();
if (pmEntry && typeof pmEntry === 'object') {
Object.keys(pmEntry).forEach(yr => yearsSet.add(yr));
}
if (lcEntry && typeof lcEntry === 'object') {
Object.keys(lcEntry).forEach(yr => yearsSet.add(yr));
}
return Array.from(yearsSet).sort();
}
function yearLayerKey(country, year) {
return `${country}-pmtiles-${year}`;
}
function yearLayerExists(country, year) {
return !!layers[yearLayerKey(country, year)];
}
// Check if country has landcover but no pmtiles (landcover-only country)
function isLandcoverOnlyCountry(country) {
return landcoverSources?.[country] && !pmTilesSources?.[country];
}
async function addYearLayer(country, year) {
// Only add pmtiles layer if the country has pmtiles data
if (pmTilesSources?.[country]?.[year]) {
await addLayer(country, 'pmtiles', year);
}
// For landcover-only countries, also enable landcover
if (isLandcoverOnlyCountry(country)) {
landcoverVisible = true;
toggleLandcoverForCountry(country, true, year);
const lc = document.getElementById('layer-landcover');
if (lc) lc.checked = true;
}
}
function removeYearLayer(country, year) {
// Only remove pmtiles layer if the country has pmtiles data
if (pmTilesSources?.[country]?.[year]) {
removeLayer(country, 'pmtiles', year);
}
// For landcover-only countries, also disable landcover
if (isLandcoverOnlyCountry(country)) {
toggleLandcoverForCountry(country, false);
const lc = document.getElementById('layer-landcover');
if (lc) lc.checked = false;
}
}
let defaultsApplied = false;
let firstInit = true;
function flyToCountry(country, opts = {}) {
if (firstInit) { firstInit = false; return; } // keep initial map center/zoom
const view = countryViews[country];
if (!view) return;
map.flyTo({ center: view.center, zoom: view.zoom, speed: 1.5 });
}
/* ===== UI: build Country / Year / Layer panels ===== */
async function buildUI() {
const toolbar = document.getElementById('toolbar');
// Panels
const countryPanel = document.createElement('div');
countryPanel.className = 'toolbar-panel';
const yearPanel = document.createElement('div');
yearPanel.className = 'toolbar-panel';
const layerPanel = document.createElement('div');
layerPanel.className = 'toolbar-panel';
// Buttons
const countryBtn = document.createElement('button');
countryBtn.className = 'toolbar-btn';
countryBtn.textContent = 'Country';
countryBtn.addEventListener('click', () => {
const show = countryPanel.style.display !== 'block';
countryPanel.style.display = show ? 'block' : 'none';
yearPanel.style.display = 'none';
layerPanel.style.display = 'none';
});
const yearBtn = document.createElement('button');
yearBtn.className = 'toolbar-btn';
yearBtn.textContent = 'Year';
yearBtn.addEventListener('click', () => {
populateYearPanel(yearPanel);
const show = yearPanel.style.display !== 'block';
yearPanel.style.display = show ? 'block' : 'none';
countryPanel.style.display = 'none';
layerPanel.style.display = 'none';
});
const layerBtn = document.createElement('button');
layerBtn.className = 'toolbar-btn';
layerBtn.textContent = 'Layer';
layerBtn.addEventListener('click', () => {
const show = layerPanel.style.display !== 'block';
layerPanel.style.display = show ? 'block' : 'none';
countryPanel.style.display = 'none';
yearPanel.style.display = 'none';
});
// Mount buttons
toolbar.appendChild(countryBtn);
toolbar.appendChild(yearBtn);
toolbar.appendChild(layerBtn);
// Mount panels
document.body.appendChild(countryPanel);
document.body.appendChild(yearPanel);
document.body.appendChild(layerPanel);
/* ---- Country Panel ---- */
Object.keys(window.MA_CONFIG.countryViews).forEach(country => {
const row = document.createElement('div');
row.className = 'panel-row';
const input = document.createElement('input');
input.type = 'checkbox';
input.id = `country-${country}`;
input.checked = (country === DEFAULT_COUNTRY);
const label = document.createElement('label');
label.setAttribute('for', input.id);
label.textContent = country;
input.addEventListener('change', async (e) => {
if (e.target.checked) {
activeCountry = country;
await addCountryBase(country);
// turn Field Boundary on (globally)
setFieldBoundaryVisibility(true);
const fb = document.getElementById('layer-field');
if (fb) fb.checked = true;
// turn Landcover on
landcoverVisible = true;
toggleLandcoverForCountry(country, true);
const lc = document.getElementById('layer-landcover');
if (lc) lc.checked = true;
// zoom to country view (center/zoom)
flyToCountry(country);
// keep Landcover synced with active country when on
if (landcoverVisible) toggleLandcoverForCountry(activeCountry, true);
// auto-open Year panel and check latest year for all countries
populateYearPanel(yearPanel);
// always auto-open Year panel when a country is selected
yearPanel.style.display = 'block';
countryPanel.style.display = 'none';
// auto-select the latest year for this country
const years = listYearsForCountry(country);
if (years.length > 0) {
const latestYear = years[years.length - 1]; // years are sorted, last is latest
const yrCheckbox = document.getElementById(`year-${country}-${latestYear}`);
if (yrCheckbox && !yrCheckbox.checked) {
yrCheckbox.checked = true;
yrCheckbox.dispatchEvent(new Event('change', { bubbles: true }));
}
}
} else {
removeCountryAll(country);
if (activeCountry === country) activeCountry = null;
}
// respect Field Boundary visibility
setFieldBoundaryVisibility(fieldBoundaryVisible);
});
row.appendChild(input);
row.appendChild(label);
countryPanel.appendChild(row);
});
const cHint = document.createElement('div');
cHint.className = 'panel-hint';
cHint.textContent = 'Turn countries on/off';
countryPanel.appendChild(cHint);
/* ---- Year Panel ---- */
function populateYearPanel(host) {
host.innerHTML = '';
if (!activeCountry) {
const msg = document.createElement('div');
msg.className = 'panel-hint';
msg.textContent = 'Choose a country first.';
host.appendChild(msg);
return;
}
const years = listYearsForCountry(activeCountry);
if (years.length === 0) {
const msg = document.createElement('div');
msg.className = 'panel-hint';
msg.textContent = `No year options for ${activeCountry}.`;
host.appendChild(msg);
return;
}
years.forEach(yr => {
const row = document.createElement('div');
row.className = 'panel-row';
const input = document.createElement('input');
input.type = 'checkbox';
input.id = `year-${activeCountry}-${yr}`;
input.checked = yearLayerExists(activeCountry, yr);
const label = document.createElement('label');
label.setAttribute('for', input.id);
label.textContent = yr;
input.addEventListener('change', async (e) => {
if (e.target.checked) {
await addYearLayer(activeCountry, yr);
} else {
removeYearLayer(activeCountry, yr);
}
setFieldBoundaryVisibility(fieldBoundaryVisible);
if (landcoverVisible) toggleLandcoverForCountry(activeCountry, true);
});
row.appendChild(input);
row.appendChild(label);
host.appendChild(row);
});
const hint = document.createElement('div');
hint.className = 'panel-hint';
if (activeCountry === 'Zambia') hint.textContent = 'Zambia: 2018–2024.';
if (activeCountry === 'Congo') hint.textContent = 'Congo: 2022.';
if (activeCountry === 'Ghana') hint.textContent = 'Ghana: 2018.';
if (activeCountry === 'Tanzania') hint.textContent = 'Tanzania: 2019.';
host.appendChild(hint);
}
/* ---- Layer Panel ---- */
// Field Boundary
const fieldRow = document.createElement('div');
fieldRow.className = 'panel-row';
const fieldCb = document.createElement('input');
fieldCb.type = 'checkbox';
fieldCb.id = 'layer-field';
fieldCb.checked = false; // Changed to false for Tanzania
const fieldLbl = document.createElement('label');
fieldLbl.setAttribute('for', 'layer-field');
fieldLbl.textContent = 'Field Boundary';
fieldCb.addEventListener('change', (e) => setFieldBoundaryVisibility(e.target.checked));
fieldRow.appendChild(fieldCb);
fieldRow.appendChild(fieldLbl);
layerPanel.appendChild(fieldRow);
// Landcover
const lcRow = document.createElement('div');
lcRow.className = 'panel-row';
const lcCb = document.createElement('input');
lcCb.type = 'checkbox';
lcCb.id = 'layer-landcover';
lcCb.checked = true; // Changed to true for Tanzania
const lcLbl = document.createElement('label');
lcLbl.setAttribute('for', 'layer-landcover');
lcLbl.textContent = 'Landcover';
lcCb.addEventListener('change', (e) => {
landcoverVisible = e.target.checked;
toggleLandcoverForCountry(activeCountry, landcoverVisible);
});
lcRow.appendChild(lcCb);
lcRow.appendChild(lcLbl);
layerPanel.appendChild(lcRow);
/*=== Defaults ===*/
if (!defaultsApplied) {
// Trigger default country checkbox change to initialize everything
const zcb = document.getElementById(`country-${DEFAULT_COUNTRY}`);
if (zcb) {
zcb.checked = true;
zcb.dispatchEvent(new Event('change', { bubbles: true }));
}
defaultsApplied = true;
}
}
/* ===== Boot ===== */
window.addEventListener('DOMContentLoaded', () => {
// PMTiles protocol
protocol = new Protocol();
maplibregl.addProtocol('pmtiles', protocol.tile);
map = new maplibregl.Map({
container: 'map',
style: {
version: 8,
sources: {
basemap: {
type: 'raster',
tiles: [maptiler],
tileSize: 256,
attribution: '© MapTiler © OpenStreetMap contributors',
maxzoom: 20
}
},
layers: [{ id: 'basemap', type: 'raster', source: 'basemap' }]
},
center: [27.8, -13.1], // Zambia
zoom: 5.5
});
map.addControl(new maplibregl.NavigationControl({ visualizePitch: true }), 'top-left');
// COG protocol
maplibregl.addProtocol('cog', MaplibreCOGProtocol.cogProtocol);
map.on('load', async () => {
// Build UI - handles all defaults (country, year, layers)
buildUI();
});
});