@metoceanapi/wxtiles-leaflet 1.1.2 → 2.0.0

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