@metoceanapi/wxtiles-leaflet 2.0.0 → 2.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,535 +0,0 @@
1
- import 'leaflet/dist/leaflet.css';
2
- import L from 'leaflet'; // goes first always!
3
-
4
- // import {
5
- // WxTilesLogging,
6
- // WxTilesLibSetup,
7
- // CreateWxTilesWatermark,
8
- // CreateWxTilesLayer,
9
- // CreateWxDebugCoordsLayer,
10
- // WxGetColorStyles,
11
- // WxTilesLayer,
12
- // LoadQTree,
13
- // Meta,
14
- // Legend,
15
- // ColorStylesStrict,
16
- // fetchJson,
17
- // WxTilesLayerSettings,
18
- // } from '../src/wxtiles';
19
- import '../src/wxtiles.css';
20
-
21
- import { Editor } from './visualStyleEditor';
22
- import { ColorStylesStrict, fetchJson } from '../src/utils/wxtools';
23
-
24
- let map: L.Map;
25
- let layerControl: L.Control.Layers;
26
- let config: Config; // application config
27
- let styles: ColorStylesStrict; // all available styles. Not every style is sutable for every layer.
28
- let globalLayer: WxTilesLayer | undefined; // current layer
29
-
30
- async function fillDataSets(defaultDataset?: string, deafaultVariable?: string) {
31
- let datasetsNames: string[];
32
-
33
- try {
34
- datasetsNames = await fetchJson<string[]>(config.dataServer + '/datasets.json');
35
- } catch (e) {
36
- console.log(e);
37
- return;
38
- }
39
-
40
- datasetsNames.sort();
41
- for (const datasetName of datasetsNames) {
42
- const opt = document.createElement('option');
43
- opt.appendChild(document.createTextNode(datasetName));
44
- opt.value = datasetName;
45
- selectDataSetEl.appendChild(opt);
46
- }
47
-
48
- defaultDataset && datasetsNames.find((n) => n === defaultDataset) && (selectDataSetEl.value = defaultDataset);
49
-
50
- await fillVariables_selectDataSetEl_onchange(deafaultVariable);
51
- }
52
-
53
- async function fillVariables_selectDataSetEl_onchange(defaultVariable?: string): Promise<void> {
54
- const oldVariable = selectVariableEl.value;
55
- selectVariableEl.innerHTML = '';
56
- let meta: Meta;
57
- try {
58
- const instances = await fetchJson(config.dataServer + '/' + selectDataSetEl.value + '/instances.json');
59
- const instance = instances[instances.length - 1];
60
- meta = await fetchJson(config.dataServer + '/' + selectDataSetEl.value + '/' + instance + '/meta.json');
61
- } catch (e) {
62
- console.log(e);
63
- return;
64
- }
65
-
66
- meta.variables.sort();
67
- for (const variable of meta.variables) {
68
- if (variable.includes('northward')) {
69
- continue;
70
- }
71
- const opt = document.createElement('option');
72
- opt.appendChild(document.createTextNode(variable.replace('eastward', 'vector')));
73
- opt.value = variable;
74
- selectVariableEl.appendChild(opt);
75
- }
76
-
77
- if (meta.variables.includes(oldVariable)) {
78
- selectVariableEl.value = oldVariable;
79
- }
80
-
81
- defaultVariable && meta.variables.find((n) => n === defaultVariable) && (selectVariableEl.value = defaultVariable);
82
-
83
- await loadVariable_selectVariableEl_onchange();
84
- }
85
-
86
- async function loadVariable_selectVariableEl_onchange(): Promise<void> {
87
- await stopPlay();
88
-
89
- const variable = selectVariableEl.value;
90
- const variables = [variable];
91
- if (variable.includes('eastward')) {
92
- variables.push(variable.replace('eastward', 'northward'));
93
- }
94
-
95
- const layerSettings: WxTilesLayerSettings = {
96
- dataSource: {
97
- serverURI: config.dataServer, // server to fetch data from
98
- maskServerURI: config.dataServer.replace(/\/data\/?/i, '/mask/{z}/{x}/{y}'),
99
- ext: config.ext, // png / webp (default) - wxtilesplitter output format
100
- dataset: selectDataSetEl.value, // dataset of the dataset
101
- variables, // variable(s) to be used for the layer rendering
102
- name: selectDataSetEl.value + '/' + selectVariableEl.selectedOptions[0].label, // attribute of the dataSource to be used externally
103
- styleName: variable, // The name of the style (from styles.json) to apply for the layer
104
- },
105
- // Lazy setup
106
- // 'true': perform setup and data loading on 'addTo(map)'.
107
- // 'false': start loading immediately, but loading is not finished when layer is created.
108
- // the signal 'setupcomplete' is fired when loading is finished.
109
- // useful when a big bunch of layers is used, so layers are not wasting memory and bandwidth.
110
- // lazy: true,
111
- // L.GridLayerOptions leaflet's options for the layer
112
- options: {
113
- opacity: 1,
114
- },
115
- };
116
-
117
- // save in order to delete old layer
118
- const oldLayer = globalLayer; // this is to store oldLayer in order a user change layers too fast.
119
- globalLayer = CreateWxTilesLayer(layerSettings);
120
- globalLayer.addTo(map);
121
- oldLayer && globalLayer.once('load', () => layerControl.removeLayer(oldLayer.removeFrom(map))); // delete old layer
122
- layerControl.addOverlay(globalLayer, layerSettings.dataSource.name);
123
-
124
- // IMPORTANT: wait for meta info to be loaded (doesn't mean 'tiles are loaded' !!!)
125
- // 1. must be befor any other operation on the layer
126
- // 2. must be after layer is added to the map
127
- await globalLayer.getSetupCompletePromise();
128
-
129
- fillTimes(globalLayer);
130
- fillStyles(globalLayer);
131
- await globalLayer.setTime(selectTimeEl.value !== '' ? selectTimeEl.value : new Date()); // try to preserve 'time' from current time of selectTimeEl
132
- }
133
-
134
- function fillTimes(layer: WxTilesLayer) {
135
- // once layer setup finished, times are available.
136
- // let's fill up 'selectTimeEl'
137
- selectTimeEl.innerHTML = '';
138
- layer.getTimes().forEach((val) => {
139
- const opt = document.createElement('option');
140
- opt.appendChild(document.createTextNode(val));
141
- opt.value = val;
142
- selectTimeEl.appendChild(opt);
143
- });
144
-
145
- selectTimeEl.value = layer.getTime();
146
- }
147
-
148
- function startPlay(): void {
149
- if (!globalLayer) return;
150
- buttonPlayStopEl.textContent = 'stop';
151
- globalLayer.setCoarseLevel(+inputCoarseLevelEl.value);
152
-
153
- // function to be called every timestep
154
- (async function nextTimeStep() {
155
- if (!globalLayer) return;
156
- if (buttonPlayStopEl.textContent === 'stop') {
157
- const start = Date.now();
158
- await globalLayer.setTime(selectTimeEl.value);
159
- updateInfoPanel(undefined);
160
- selectTimeEl.selectedIndex++;
161
- selectTimeEl.selectedIndex %= selectTimeEl.length;
162
- const dt = +inputAnimDelayEl.value - (Date.now() - start);
163
- setTimeout(nextTimeStep, dt < 0 ? 0 : dt);
164
- }
165
- })();
166
- }
167
-
168
- async function stopPlay() {
169
- if (buttonPlayStopEl.textContent !== 'play') {
170
- buttonPlayStopEl.textContent = 'play';
171
- return globalLayer?.unsetCoarseLevel();
172
- }
173
-
174
- return;
175
- }
176
-
177
- function addOption(baseStyle: string, value = baseStyle) {
178
- const opt = document.createElement('option');
179
- opt.appendChild(document.createTextNode(baseStyle));
180
- opt.value = value;
181
- selectStyleEl.appendChild(opt);
182
- }
183
-
184
- function fillStyles(layer: WxTilesLayer) {
185
- selectStyleEl.innerHTML = '';
186
- if (config.varToStyleMap) {
187
- for (const [regexp, styleName] of config.varToStyleMap) {
188
- const regExp = new RegExp(regexp, 'i');
189
- if (styleName in styles && regExp.test(layer.dataSource.variables[0])) {
190
- addOption(styles[styleName].name, styleName);
191
- }
192
- }
193
- }
194
-
195
- addOption('base');
196
- addOption('custom');
197
- onStyleChange_selectStyleEl_onchange();
198
- }
199
-
200
- function onStyleChange_selectStyleEl_onchange() {
201
- if (!globalLayer) return;
202
- if (selectStyleEl.value === 'custom') {
203
- const style = editor.getStyle();
204
- if (style instanceof Error) {
205
- console.log('Wrong custom style');
206
- const ctx = legendCanvasEl.getContext('2d');
207
- if (!ctx) return;
208
- ctx.clearRect(0, 0, legendCanvasEl.width, legendCanvasEl.height);
209
- ctx.beginPath();
210
- ctx.font = legendCanvasEl.height / 2 + 'px sans-serif';
211
- ctx.fillText('Wrong custom style', 10, legendCanvasEl.height / 2);
212
- ctx.stroke();
213
- return;
214
- }
215
- styles.custom = style; //JSON.parse(customStyleTextAreaEl.value);
216
- }
217
-
218
- globalLayer.setStyle(selectStyleEl.value);
219
- const curStyle = globalLayer.getStyle();
220
- // customStyleTextAreaEl.value = JSON.stringify(JSONsort(curStyle), null, ' ');
221
- editor.setStyle(curStyle);
222
- const legend = globalLayer.getLegendData(legendCanvasEl.width - 50);
223
- if (!legend) return;
224
- drawLegend({ legend, canvas: legendCanvasEl });
225
- }
226
-
227
- function drawLegend({ legend, canvas }: { legend: Legend; canvas: HTMLCanvasElement }) {
228
- if (!globalLayer || !canvas || !legend) return;
229
-
230
- const { width, height } = canvas;
231
- const halfHeight = (16 + height) >> 2;
232
-
233
- // draw legend
234
- const ctx = canvas.getContext('2d')!;
235
- const imData = ctx.createImageData(width, height);
236
- const im = new Uint32Array(imData.data.buffer);
237
- im.fill(-1);
238
-
239
- const startX = 2;
240
- const startY = 2;
241
- const startXY = startX + width * startY;
242
-
243
- const trSize = halfHeight >> 1;
244
- // left triangle
245
- if (legend.showBelowMin) {
246
- const c = legend.colors[0];
247
- if (c) {
248
- for (let x = 0; x < trSize; ++x) {
249
- for (let y = trSize; y < trSize + x; ++y) {
250
- im[startXY + x + y * width] = c;
251
- im[startXY + x + (trSize * 2 - y) * width] = c;
252
- }
253
- }
254
- }
255
- }
256
-
257
- for (let x = 0; x < legend.size; ++x) {
258
- for (let y = 0; y < halfHeight; ++y) {
259
- if (legend.colors[0]) {
260
- im[startX + x + trSize + (y + startY + 1) * width] = legend.colors[x];
261
- }
262
- }
263
- }
264
-
265
- // right triangle
266
- if (legend.showAboveMax) {
267
- const c = legend.colors[legend.colors.length - 1];
268
- if (c) {
269
- for (let x = 0; x <= trSize; ++x) {
270
- for (let y = trSize; y < trSize + x; ++y) {
271
- im[startXY + trSize * 2 + legend.size - x + y * width] = c;
272
- im[startXY + trSize * 2 + legend.size - x + (trSize * 2 - y) * width] = c;
273
- }
274
- }
275
- }
276
- }
277
-
278
- ctx.putImageData(imData, 0, 0);
279
-
280
- // draw ticks
281
- ctx.font = '8px sans-serif';
282
- ctx.beginPath();
283
- for (const tick of legend.ticks) {
284
- ctx.strokeStyle = '#000';
285
- ctx.moveTo(tick.pos + trSize + startX + 1, startY + 3);
286
- ctx.lineTo(tick.pos + trSize + startX + 1, halfHeight);
287
- ctx.fillText(tick.dataString, tick.pos + trSize + startX + 1, halfHeight + 11);
288
- }
289
-
290
- ctx.font = '12px sans-serif';
291
- const txt = `${globalLayer.getStyle().name} (${legend.units})`;
292
- ctx.fillText(txt, 13, height - 5);
293
- ctx.stroke();
294
-
295
- ctx.strokeStyle = '#888';
296
- ctx.strokeRect(1, 1, width - 3, height - 2); //for white background
297
- }
298
-
299
- let oldE: L.LeafletMouseEvent;
300
- function updateInfoPanel(e: L.LeafletMouseEvent | undefined) {
301
- // save 'e'
302
- if (e) oldE = e;
303
- else e = oldE; // restore 'e'
304
- let content = `${e.latlng}<br>`;
305
- // TODO
306
- // map.eachLayer((layer) => {
307
- // if (layer instanceof WxTilesLayer) {
308
- // const tile = layer.getLayerInfoAtLatLon(e!.latlng);
309
- // const { min, max } = layer.getMinMax();
310
- // const ltime = layer.getTime();
311
- // content += tile
312
- // ? `<div>
313
- // <div style="width:1em;height:1em;float:left;margin-right:2px;background:${tile.hexColor}"></div>
314
- // ${layer.dataSource.name}=${tile.inStyleUnits.map((d) => d.toFixed(2)).join(',')} ${tile.styleUnits} (${min.toFixed(2)}, ${max.toFixed(2)}), time: ${ltime}<br>
315
- // </div>`
316
- // : '';
317
- // }
318
- // });
319
-
320
- infoPanelEl.innerHTML = content;
321
- }
322
-
323
- function popupInfo(e: L.LeafletMouseEvent) {
324
- let content = '';
325
- // TODO
326
- // map.eachLayer((layer) => {
327
- // if (layer instanceof WxTilesLayer) {
328
- // const tile = layer.getLayerInfoAtLatLon(e.latlng);
329
- // const time = layer.getTime();
330
- // content += tile
331
- // ? `<div>
332
- // <div style="width:1em;height:1em;float:left;margin-right:2px;background:${tile.hexColor}"></div>
333
- // ${layer.dataSource.name}<br>
334
- // (in style Units = ${tile.inStyleUnits} ${tile.styleUnits})<br>
335
- // (in data Units = ${tile.data} ${layer.state.units})<br>
336
- // (time:${time})<br>
337
- // (instance:${layer.state.instance})<br>
338
- // (tilePoint:${tile.tilePoint.x},${tile.tilePoint.y})<br>
339
- // </div>`
340
- // : '';
341
- // // (tileCoords:${tile.tile.coords.x},${tile.tile.coords.y},zoom:${tile.tile.coords.z})<br>
342
- // }
343
- // });
344
-
345
- L.popup()
346
- .setLatLng(e.latlng)
347
- .setContent(content + `${e.latlng}`)
348
- .openOn(map);
349
- }
350
-
351
- function createControl(opt: L.ControlOptions & { htmlID: string }): L.Control {
352
- return new (L.Control.extend({
353
- onAdd() {
354
- return document.getElementById(opt.htmlID);
355
- },
356
- }))(opt);
357
- }
358
-
359
- interface BaseLayerOptions {
360
- name: string;
361
- URL: string;
362
- options?: L.TileLayerOptions;
363
- add?: boolean;
364
- }
365
- interface Config {
366
- dataServer: string;
367
- ext: 'webp' | 'png';
368
- map?: L.MapOptions;
369
- baseLayers?: BaseLayerOptions[];
370
- varToStyleMap?: [string, string][];
371
- }
372
-
373
- async function start() {
374
- // read config
375
- try {
376
- config = await fetchJson('props/config.json'); // set the correct URI
377
- } catch (e) {
378
- console.log(e);
379
- alert('No props/config.json');
380
- return;
381
- }
382
-
383
- // Leaflet basic setup // set the main Leaflet's map object, compose and add base layers
384
- map = L.map('map', config.map);
385
-
386
- const styleEditorEl = document.getElementById('styleEditor');
387
- if (!styleEditorEl) {
388
- throw new Error('styleEditorEl not found');
389
- }
390
-
391
- // Setup WxTiles lib
392
- WxTilesLogging(true); // use wxtiles logging -> console.log
393
- CreateWxTilesWatermark({ URI: 'res/wxtiles-logo.png', position: 'topright' }).addTo(map);
394
- layerControl = L.control.layers(undefined, undefined, { position: 'topright', autoZIndex: false, collapsed: false }).addTo(map);
395
- config.baseLayers?.map((baseLayer) => {
396
- if (!baseLayer.add) return;
397
- const layer = L.tileLayer(baseLayer.URL, baseLayer.options);
398
- baseLayer.options?.zIndex === 0 ? layerControl.addBaseLayer(layer, baseLayer.name) : layerControl.addOverlay(layer, baseLayer.name);
399
- });
400
- layerControl.addOverlay(CreateWxDebugCoordsLayer(), 'tile boundaries');
401
- layerControl.addBaseLayer(L.tileLayer('').addTo(map), 'base-empty');
402
-
403
- createControl({ position: 'topleft', htmlID: 'legend' }).addTo(map);
404
- createControl({ position: 'topleft', htmlID: 'layerPanel' }).addTo(map);
405
- createControl({ position: 'topleft', htmlID: 'styleEditor' }).addTo(map);
406
- createControl({ position: 'bottomright', htmlID: 'infoPanel' }).addTo(map);
407
-
408
- const wxlibCustomSettings: any = {};
409
- try {
410
- // these URIs are for the demo purpose. set the correct URI
411
- wxlibCustomSettings.colorStyles = await fetchJson('props/styles.json'); // set the correct URI
412
- } catch (e) {
413
- console.log(e);
414
- }
415
-
416
- try {
417
- wxlibCustomSettings.units = await fetchJson('props/uconv.json'); // set the correct URI
418
- } catch (e) {
419
- console.log(e);
420
- }
421
-
422
- try {
423
- wxlibCustomSettings.colorSchemes = await fetchJson('props/colorschemes.json'); // set the correct URI
424
- } catch (e) {
425
- console.log(e);
426
- }
427
-
428
- // ESSENTIAL step to get lib ready.
429
- WxTilesLibSetup(wxlibCustomSettings); // load fonts and styles, units, colorschemas - empty => defaults
430
- await document.fonts.ready; // !!! IMPORTANT: make sure fonts (barbs, arrows, etc) are loaded
431
- await LoadQTree(config.dataServer + 'seamask.qtree');
432
-
433
- styles = WxGetColorStyles(); // all available styles. Not every style is sutable for this layer.
434
-
435
- fillDataSets('gfs.global', 'wind.speed.eastward.at-10m');
436
- // fillDataSets('gfs.global', 'air.temperature.at-2m');
437
-
438
- map.on('zoom', stopPlay); // stop time animation on zoom
439
- map.on('mousemove', updateInfoPanel);
440
- map.on('click', popupInfo);
441
- editor = new Editor(map, styleEditorEl, selectStyleEl, { id: 'visualCustomStyleDivId', className: 'visualCustomStyleDivClass' });
442
- editor.onchange = (style) => {
443
- selectStyleEl.value = 'custom';
444
- styles['custom'] = style;
445
- // globalLayer?.setStyle('custom');
446
- onStyleChange_selectStyleEl_onchange();
447
- };
448
- }
449
-
450
- const selectDataSetEl = document.getElementById('selectDataSet') as HTMLSelectElement;
451
- selectDataSetEl.addEventListener('change', () => {
452
- fillVariables_selectDataSetEl_onchange();
453
- });
454
-
455
- const selectVariableEl = document.getElementById('selectVariable') as HTMLSelectElement;
456
- selectVariableEl.addEventListener('change', loadVariable_selectVariableEl_onchange);
457
-
458
- const selectStyleEl = document.getElementById('selectStyle') as HTMLSelectElement;
459
- selectStyleEl.addEventListener('change', onStyleChange_selectStyleEl_onchange);
460
-
461
- const legendCanvasEl = document.getElementById('legend') as HTMLCanvasElement;
462
-
463
- // const customStyleDivEl = document.getElementById('customStyleDiv') as HTMLDivElement;
464
- // const customStyleTextAreaEl = document.getElementById('customStyleTextArea') as HTMLTextAreaElement;
465
- // const editor = createEditor(customStyleDivEl, 'visualCustomStyleDivId', 'visualCustomStyleDivClass');
466
- let editor: Editor; // = new Editor(map, customStyleDivEl, 'visualCustomStyleDivId', 'visualCustomStyleDivClass');
467
- // editor.onchange = (style) => {
468
- // selectStyleEl.value = 'custom';
469
- // customStyleTextAreaEl.value = JSON.stringify(style, null, ' ');
470
- // onStyleChange_selectStyleEl_onchange();
471
- // };
472
- // customStyleTextAreaEl.addEventListener('change', () => {
473
- // selectStyleEl.value = 'custom';
474
- // onStyleChange_selectStyleEl_onchange();
475
- // });
476
-
477
- // const customStyleButtonEl = document.getElementById('customStyleButton')! as HTMLButtonElement;
478
- // customStyleButtonEl.addEventListener('click', () => {
479
- // if (customStyleDivEl.style.display != 'none') {
480
- // customStyleDivEl.style.display = 'none';
481
- // customStyleButtonEl.innerHTML = 'show Custom Style Editor';
482
- // } else {
483
- // customStyleDivEl.style.display = 'block';
484
- // customStyleButtonEl.innerHTML = 'update Custom Style & Hide';
485
- // selectStyleEl.value = 'custom';
486
- // }
487
- // });
488
-
489
- const selectTimeEl = document.getElementById('selectTime') as HTMLSelectElement;
490
- selectTimeEl.addEventListener('change', async () => {
491
- if (!globalLayer) return;
492
- if (buttonPlayStopEl.textContent === 'stop') await stopPlay();
493
- selectTimeEl.style.backgroundColor = '#fa0';
494
- await globalLayer.setTime(selectTimeEl.value);
495
- selectTimeEl.style.backgroundColor = '#fff';
496
- selectTimeEl.value = globalLayer.getTime();
497
- updateInfoPanel(undefined);
498
- });
499
-
500
- const buttonHoldEl = document.getElementById('buttonHold') as HTMLButtonElement;
501
- buttonHoldEl.addEventListener('click', () => {
502
- L.popup()
503
- .setLatLng(map.getCenter())
504
- .setContent(
505
- `
506
- This layer was "held".
507
- You can hold as many layers as you want, but you can't control them after holding.
508
- New layers will appear OVER the held layers.
509
- Use the "clear" button to clear the ALL VISIBLE layers.
510
- `
511
- )
512
- .openOn(map);
513
- stopPlay();
514
- globalLayer = undefined;
515
- });
516
-
517
- const infoPanelEl = document.getElementById('infoPanel') as HTMLDivElement;
518
- const inputAnimDelayEl = document.getElementById('animDelay') as HTMLInputElement;
519
- const inputCoarseLevelEl = document.getElementById('coarseLevel') as HTMLInputElement;
520
- const buttonPlayStopEl = document.getElementById('buttonPlayStop') as HTMLButtonElement;
521
- buttonPlayStopEl.addEventListener('click', () => {
522
- buttonPlayStopEl.textContent === 'play' ? startPlay() : stopPlay();
523
- });
524
- const clearEl = document.getElementById('buttonClear')!;
525
- clearEl.addEventListener('click', () => {
526
- map.eachLayer((l) => {
527
- if ('getTile' in l) {
528
- l.removeFrom(map);
529
- layerControl.removeLayer(l);
530
- }
531
- });
532
- loadVariable_selectVariableEl_onchange();
533
- });
534
-
535
- start();