@metoceanapi/wxtiles-leaflet 2.0.8 → 2.1.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metoceanapi/wxtiles-leaflet",
3
- "version": "2.0.8",
3
+ "version": "2.1.0",
4
4
  "description": "WxTile JS lib to render wxtiles datalayers",
5
5
  "main": "dist/es/index.js",
6
6
  "types": "dist/es/index.d.ts",
@@ -0,0 +1,69 @@
1
+ import L from 'leaflet';
2
+ import { WxGetColorStyles } from '../src';
3
+
4
+ export function flyTo(map: L.Map, zoom: number, lng: number, lat: number, bearing: number, pitch: number) {
5
+ map.flyTo([lat, lng], zoom);
6
+ }
7
+
8
+ export function setURL(map: L.Map, time: string, datasetName: string, variable: string, style: any) {
9
+ const base = WxGetColorStyles()['base'];
10
+ for (const i in style) style[i] === base[i] && delete style[i]; // remove default values
11
+
12
+ const center = map.getCenter().wrap();
13
+ const href =
14
+ `##${datasetName}/${variable}/${time}/${map.getZoom().toFixed(2)}/${center.lng.toFixed(2)}/${center.lat.toFixed(2)}/0/0` +
15
+ (style ? '/' + JSON.stringify(style) : '');
16
+
17
+ history.replaceState(null, '', href);
18
+ // location.href = `#${datasetName}/${variables.join(',')}/${time}/${map.getZoom().toFixed(2)}/${center.lng.toFixed(2)}/${center.lat.toFixed(2)}`;
19
+ }
20
+
21
+ export async function initFrameWork() {
22
+ const map = L.map('map', {
23
+ center: [-40.75, 174.5],
24
+ zoom: 7,
25
+ zoomControl: false,
26
+ });
27
+
28
+ L.control.zoom({ position: 'bottomright' }).addTo(map);
29
+
30
+ // class WxDebugLayer extends L.GridLayer {
31
+ // createTile(coords: { x: number; y: number; z: number }) {
32
+ // const tile = document.createElement('div');
33
+ // tile.innerHTML = [coords.x, coords.y, coords.z].join(', ');
34
+ // tile.style.outline = '1px solid red';
35
+ // return tile;
36
+ // }
37
+ // }
38
+ // map.addLayer(new WxDebugLayer().setZIndex(1000));
39
+
40
+ return map;
41
+ }
42
+
43
+ export function addControl(map: L.Map, control: { extender: () => any }, position: string) {
44
+ position = position.replace('-', '');
45
+ map.addControl(new (L.Control.extend(control.extender()))({ position: position as any }));
46
+ }
47
+
48
+ export function position(e: L.LeafletMouseEvent): L.LatLng {
49
+ return e.latlng.wrap(); // (mapbox)
50
+ }
51
+
52
+ export function removeLayer(map: L.Map, layerId: string, layer?: L.Layer) {
53
+ map.eachLayer((l: any) => {
54
+ if (l.options.id === layerId) {
55
+ map.removeLayer(l);
56
+ }
57
+ });
58
+ }
59
+
60
+ export async function addLayer(map: L.Map, idS: string, idL: string, layer: L.Layer) {
61
+ map.addLayer(layer);
62
+ await new Promise((done) => layer.once('load', done)); // highly recommended to await for the first load
63
+ console.log('layer loaded', idS, idL);
64
+ }
65
+
66
+ export function addRaster(map: L.Map, idS: string, idL: string, URL: string, maxZoom: number) {
67
+ const layer = L.tileLayer(URL, { id: idS, maxNativeZoom: maxZoom, zIndex: idL === 'baseL' ? 100 : 0 });
68
+ map.addLayer(layer);
69
+ }
@@ -1,291 +1,14 @@
1
1
  import 'leaflet/dist/leaflet.css';
2
- import L from 'leaflet'; // goes first always!
3
-
4
- import { WxTileSource, type WxVars, WxAPI, WxTilesLogging, type WxTileInfo, FrameworkOptions, WxGetColorStyles, WXLOG, WxColorStyleWeak } from '../src/index';
5
- import { WxLegendControl } from '../src/controls/WxLegendControl';
6
- import { WxStyleEditorControl } from '../src/controls/WxStyleEditorControl';
7
- import { WxInfoControl } from '../src/controls/WxInfoControl';
8
- import { WxTimeControl } from '../src/controls/WxTimeControl ';
9
- import { WxAPIControl } from '../src/controls/WxAPIControl';
10
2
 
3
+ import { start } from './start';
11
4
  start();
5
+
6
+ /*
7
+ import L from 'leaflet'; // goes first always!
8
+ import { WxTileSource, WxAPI, WxTilesLogging, FrameworkOptions } from '../src/index';
12
9
  // simpleDemo();
13
10
  // twoLayersDemo();
14
11
 
15
- const OPACITY = 1;
16
-
17
- // this is universal function for Leaflet and Mapbox.
18
- // Functions below are just framework specific wrappers for this universal function
19
- // start() is the fully interchangable function for Leaflet and Mapbox
20
- async function start() {
21
- const map = await initFrameWork();
22
- addRaster(map, 'baseS', 'baseL', 'https://tiles.metoceanapi.com/base-lines/{z}/{x}/{y}', 5);
23
- WxTilesLogging(false);
24
- // const dataServerURL = 'http://localhost:9191/data/';
25
- const dataServerURL = 'https://tiles.metoceanapi.com/data/';
26
- // const dataServerURL = 'http://tiles3.metoceanapi.com/';
27
- const myHeaders = new Headers();
28
- // myHeaders.append('x-api-key', 'SpV3J1RypVrv2qkcJE91gG');
29
- const wxapi = new WxAPI({
30
- dataServerURL,
31
- maskURL: dataServerURL + 'masks/{z}/{x}/{y}.png',
32
- maskChannel: 'R',
33
- maskDepth: 9, // currently only max 9 is supported
34
- qtreeURL: dataServerURL + 'masks/9+1.seamask.qtree',
35
- requestInit: { headers: myHeaders },
36
- });
37
-
38
- let datasetName = 'gfs.global'; /* 'mercator.global/'; */ /* 'ecwmf.global/'; */ /* 'obs-radar.rain.nzl.national/'; */
39
- let variable = 'air.temperature.at-2m';
40
- // let variables: WxVars = ['wind.speed.eastward.at-10m', 'wind.speed.northward.at-10m'];
41
-
42
- // let datasetName = 'ww3-ecmwf.global';
43
- // let variables: WxVars = ['wave.direction.mean'];
44
-
45
- // let datasetName = 'obs-radar.rain.nzl.national';
46
- // let variables: WxVars = ['reflectivity'];
47
-
48
- // get datasetName from URL
49
- const urlParams = window.location.toString().split('##')[1];
50
- const params = urlParams?.split('/');
51
- datasetName = params?.[0] || datasetName;
52
- if (params?.[1]) variable = params[1];
53
- let time = params?.[2] || '';
54
- const zoom = (params && parseFloat(params[3])) || 0;
55
- const lng = (params && parseFloat(params[4])) || 0;
56
- const lat = (params && parseFloat(params[5])) || 0;
57
- const bearing = (params && parseFloat(params[6])) || 0;
58
- const pitch = (params && parseFloat(params[7])) || 0;
59
- if (params?.length > 8) params[8] = params.slice(8).join('/');
60
-
61
- const str = params?.[8] && params[8];
62
- const sth = { style: {} as WxColorStyleWeak };
63
- try {
64
- // get style from URL
65
- sth.style = str && { ...JSON.parse(decodeURI(str)) }; // reset levels if change units
66
- } catch (e) {
67
- /* ignore errors silently */
68
- console.log(e);
69
- }
70
-
71
- flyTo(map, zoom, lng, lat, bearing, pitch);
72
-
73
- // const sth = { style: {} };
74
- map.on('zoom', () => setURL(map, time, datasetName, variable, sth.style));
75
- map.on('drag', () => setURL(map, time, datasetName, variable, sth.style));
76
- map.on('rotate', () => setURL(map, time, datasetName, variable, sth.style));
77
- map.on('pitch', () => setURL(map, time, datasetName, variable, sth.style));
78
-
79
- let wxsource: WxTileSource | undefined;
80
-
81
- const legendControl = new WxLegendControl();
82
- addControl(map, legendControl, 'top-right');
83
-
84
- const frameworkOptions = { id: 'wxsource', opacity: OPACITY, attribution: 'WxTiles' };
85
- const apiControl = new WxAPIControl(wxapi, datasetName, variable);
86
- addControl(map, apiControl, 'top-left');
87
- apiControl.onchange = async (datasetName_, variable_, nonnativecall): Promise<void> => {
88
- WXLOG('apiControl.onchange datasetName=', datasetName_, 'variable=', variable_);
89
- // remove existing source and layer
90
- removeLayer(map, frameworkOptions.id, wxsource);
91
- //
92
- nonnativecall || (sth.style = {}); // reset style if change dataset/variable
93
- wxsource = undefined;
94
- datasetName = datasetName_;
95
- variable = variable_;
96
- const wxdatasetManager = await wxapi.createDatasetManager(datasetName);
97
- const meta = wxdatasetManager.getVariableMeta(variable);
98
- if (meta?.units === 'RGB') {
99
- addRaster(map, frameworkOptions.id, 'wxtiles', wxdatasetManager.createURI(variable, 0), wxdatasetManager.getMaxZoom());
100
- timeControl.setTimes(wxdatasetManager.getTimes());
101
- legendControl.clear();
102
- } else {
103
- wxsource = wxdatasetManager.createSourceLayer({ variable, time, wxstyle: sth.style }, frameworkOptions);
104
- await addLayer(map, frameworkOptions.id, 'wxtiles', wxsource);
105
- const styleCopy = wxsource.getCurrentStyleObjectCopy();
106
- legendControl.drawLegend(styleCopy); // first draw legend with current style
107
- styleCopy.levels = sth.style?.levels; // no need to show defaults it in the editor and URL
108
- styleCopy.colors = sth.style?.colors; // no need to show defaults it in the editor and URL
109
- await customStyleEditorControl.onchange?.(styleCopy, true);
110
- }
111
-
112
- timeControl.updateSource(wxsource);
113
- };
114
-
115
- const timeControl = new WxTimeControl(50);
116
- addControl(map, timeControl, 'top-left');
117
- timeControl.onchange = (time_) => {
118
- setURL(map, (time = time_), datasetName, variable, sth.style);
119
- };
120
-
121
- const customStyleEditorControl = new WxStyleEditorControl();
122
- addControl(map, customStyleEditorControl, 'top-right');
123
- customStyleEditorControl.onchange = async (style, nonnativecall) => {
124
- WXLOG('customStyleEditorControl.onchange');
125
- if (!wxsource) return;
126
- nonnativecall || (await wxsource.updateCurrentStyleObject(style)); // if called manually, do not update wxsource's style
127
- const nstyle = wxsource.getCurrentStyleObjectCopy();
128
- legendControl.drawLegend(nstyle);
129
- nstyle.levels = style?.levels; // keep levels empty if they are not defined
130
- nstyle.colors = style?.colors; // keep colors empty if they are not defined
131
- customStyleEditorControl.setStyle(nstyle); // if called from wxsource, update customStyleEditorControl
132
- sth.style = nstyle;
133
- setURL(map, time, datasetName, variable, sth.style);
134
- };
135
-
136
- const infoControl = new WxInfoControl();
137
- addControl(map, infoControl, 'bottom-left');
138
- map.on('mousemove', (e) => infoControl.update(wxsource, map, position(e)));
139
-
140
- await apiControl.onchange(datasetName, variable, true); // initial load
141
-
142
- /*/ DEMO: more interactive - additional level and a bit of the red transparentness around the level made from current mouse position
143
- if (wxsource) {
144
- let busy = false;
145
- await wxsource.updateCurrentStyleObject({ levels: undefined }); // await always !!
146
- const levels = wxsource.getCurrentStyleObjectCopy().levels || []; // get current/default/any levels
147
- const colMap: [number, string][] = levels.map((level) => [level, '#' + Math.random().toString(16).slice(2, 8) + 'ff']);
148
- map.on('mousemove', async (e) => {
149
- if (!wxsource || busy) return;
150
- busy = true;
151
- const tileInfo: WxTileInfo | undefined = wxsource.getLayerInfoAtLatLon(position(e), map);
152
- if (tileInfo) {
153
- await customStyleEditorControl.onchange?.({ colorMap: [...colMap, [tileInfo.inStyleUnits[0], '#ff000000']] }); // await always !!
154
- }
155
- busy = false;
156
- });
157
- } //*/
158
-
159
- /*/ DEMO: abort
160
- if (wxsource) {
161
- const abortController = new AbortController();
162
- console.log('setTime(5)');
163
- const prom = wxsource.setTime(5, abortController);
164
- abortController.abort(); // aborts the request
165
- await prom; // await always !! even if aborted
166
- console.log('aborted');
167
- await wxsource.setTime(5); // no abort
168
- console.log('setTime(5) done');
169
- }//*/
170
-
171
- /*/ DEMO: preload a timestep
172
- map.once('click', async () => {
173
- if (!wxsource) return;
174
- console.log('no preload time=5');
175
- const t = Date.now();
176
- await wxsource.setTime(5); // await always !! or abort
177
- console.log(Date.now() - t);
178
- await wxsource.preloadTime(10); // await always !! even if aborted
179
- await wxsource.preloadTime(20); // await always !! even if aborted
180
- console.log('preloaded timesteps 10, 20');
181
- map.once('click', async () => {
182
- if (!wxsource) return;
183
- const t = Date.now();
184
- await wxsource.setTime(10); // await always !! or abort
185
- console.log(Date.now() - t, ' step 10');
186
- map.once('click', async () => {
187
- if (!wxsource) return;
188
- const t = Date.now();
189
- await wxsource.setTime(20); // await always !! or abort
190
- console.log(Date.now() - t, ' step 20');
191
- });
192
- });
193
- }); //*/
194
-
195
- /*/ DEMO: change style's units
196
- let i = 0;
197
- map.on('click', async () => {
198
- if (!wxsource) return;
199
- const u = ['knots', 'm/s', 'km/h', 'miles/h'];
200
- await wxsource.updateCurrentStyleObject({ units: u[i], levels: undefined }); // levels: undefined - to recalculate levels
201
- legendControl.drawLegend(wxsource.getCurrentStyleObjectCopy());
202
- i = (i + 1) % u.length;
203
- }); //*/
204
-
205
- /*/ DEMO : read lon lat data
206
- map.on('mousemove', (e) => {
207
- if (!wxsource) return;
208
- const pos = position(e); //
209
- const tileInfo: WxTileInfo | undefined = wxsource.getLayerInfoAtLatLon(pos.wrap(), map);
210
- if (tileInfo) {
211
- console.log(tileInfo);
212
- }
213
- }); //*/
214
-
215
- /*/ DEMO: timesteps
216
- let t = 0;
217
- const nextTimeStep = async () => {
218
- if (!wxsource) return;
219
- await wxsource.setTime(t++ % wxsource.wxdatasetManager.getTimes().length); // await always !!
220
- setTimeout(nextTimeStep, 0);
221
- };
222
- setTimeout(nextTimeStep, 2000);
223
- //*/
224
-
225
- /*/ DEMO: Dynamic blur effect /
226
- wxsource &&
227
- (async function step(n: number = 0) {
228
- await wxsource.updateCurrentStyleObject({ isolineText: false, blurRadius: ~~(10 * Math.sin(n / 500) + 10) }); // await always !!
229
- requestAnimationFrame(step);
230
- })();
231
- //*/
232
- }
233
-
234
- function flyTo(map: L.Map, zoom: number, lng: number, lat: number, bearing: number, pitch: number) {
235
- map.flyTo([lat, lng], zoom);
236
- }
237
-
238
- function setURL(map: L.Map, time: string, datasetName: string, variable: string, style: any) {
239
- const base = WxGetColorStyles()['base'];
240
- for (const i in style) style[i] === base[i] && delete style[i]; // remove default values
241
-
242
- const center = map.getCenter().wrap();
243
- const href =
244
- `##${datasetName}/${variable}/${time}/${map.getZoom().toFixed(2)}/${center.lng.toFixed(2)}/${center.lat.toFixed(2)}/0/0` +
245
- (style ? '/' + JSON.stringify(style) : '');
246
-
247
- history.replaceState(null, '', href);
248
- // location.href = `#${datasetName}/${variables.join(',')}/${time}/${map.getZoom().toFixed(2)}/${center.lng.toFixed(2)}/${center.lat.toFixed(2)}`;
249
- }
250
-
251
- async function initFrameWork() {
252
- const map = L.map('map', {
253
- center: [-40.75, 174.5],
254
- zoom: 3,
255
- zoomControl: false,
256
- });
257
-
258
- L.control.zoom({ position: 'bottomright' }).addTo(map);
259
- return map;
260
- }
261
-
262
- function addControl(map: L.Map, control: { extender: () => any }, position: string) {
263
- position = position.replace('-', '');
264
- map.addControl(new (L.Control.extend(control.extender()))({ position: position as any }));
265
- }
266
-
267
- function position(e: L.LeafletMouseEvent): L.LatLng {
268
- return e.latlng.wrap(); // (mapbox)
269
- }
270
-
271
- function removeLayer(map: L.Map, layerId: string, layer?: L.Layer) {
272
- map.eachLayer((l: any) => {
273
- if (l.options.id === layerId) {
274
- map.removeLayer(l);
275
- }
276
- });
277
- }
278
-
279
- async function addLayer(map: L.Map, idS: string, idL: string, layer: L.Layer) {
280
- map.addLayer(layer);
281
- await new Promise((done) => layer.once('load', done)); // highly recommended to await for the first load
282
- }
283
-
284
- function addRaster(map: L.Map, idS: string, idL: string, URL: string, maxZoom: number) {
285
- const layer = L.tileLayer(URL, { id: idS, maxNativeZoom: maxZoom, zIndex: idL === 'baseL' ? 100 : 0 });
286
- map.addLayer(layer);
287
- }
288
-
289
12
  async function simpleDemo() {
290
13
  const map = L.map('map', { center: [0, 0], zoom: 2, zoomControl: true });
291
14
 
@@ -293,7 +16,7 @@ async function simpleDemo() {
293
16
  // const headers = new Headers();
294
17
  // headers.append('x-api-key', '--proper-key-value--'); // If needed in the future
295
18
  const requestInit: RequestInit = {
296
- /* headers */
19
+ // headers //
297
20
  }; // add more options if needed such as headers, mode, credentials, etc
298
21
 
299
22
  // Get the API ready - should be ONE per application
@@ -352,3 +75,4 @@ async function twoLayersDemo() {
352
75
  // add the group to the control layer
353
76
  control.addOverlay(group, 'wxsources group');
354
77
  }
78
+ */
@@ -0,0 +1,232 @@
1
+ import { WxTileSource, type WxVars, WxAPI, WxTilesLogging, type WxTileInfo, FrameworkOptions, WxGetColorStyles, WXLOG, WxColorStyleWeak } from '../src/index';
2
+ import { WxLegendControl } from '../src/controls/WxLegendControl';
3
+ import { WxStyleEditorControl } from '../src/controls/WxStyleEditorControl';
4
+ import { WxInfoControl } from '../src/controls/WxInfoControl';
5
+ import { WxTimeControl } from '../src/controls/WxTimeControl ';
6
+ import { WxAPIControl } from '../src/controls/WxAPIControl';
7
+ import { initFrameWork, addRaster, flyTo, setURL, addControl, removeLayer, addLayer, position } from './frwrkdeps';
8
+
9
+ export const OPACITY = 0.8;
10
+
11
+ // this is universal function for Leaflet and Mapbox.
12
+ // Functions below are just framework specific wrappers for this universal function
13
+ // start() is the fully interchangable function for Leaflet and Mapbox
14
+ export async function start() {
15
+ const map = await initFrameWork();
16
+ addRaster(map, 'baseS', 'baseL', 'https://tiles.metoceanapi.com/base-lines/{z}/{x}/{y}', 5);
17
+ WxTilesLogging(false);
18
+ // const dataServerURL = 'http://localhost:9191/data/';
19
+ // const dataServerURL = 'https://68.171.214.87/data/'
20
+ const dataServerURL = 'https://tiles.metoceanapi.com/data/';
21
+ // const dataServerURL = 'http://tiles3.metoceanapi.com/';
22
+ const myHeaders = new Headers();
23
+ // myHeaders.append('x-api-key', 'SpV3J1RypVrv2qkcJE91gG');
24
+ const wxapi = new WxAPI({
25
+ dataServerURL,
26
+ maskURL: 'auto',
27
+ maskChannel: 'R',
28
+ qtreeURL: 'auto',
29
+ requestInit: { headers: myHeaders },
30
+ });
31
+
32
+ let datasetName = 'gfs.global'; /* 'mercator.global/'; */ /* 'ecwmf.global/'; */ /* 'obs-radar.rain.nzl.national/'; */
33
+ let variable = 'air.temperature.at-2m';
34
+ // let variables: WxVars = ['wind.speed.eastward.at-10m', 'wind.speed.northward.at-10m'];
35
+
36
+ // let datasetName = 'ww3-ecmwf.global';
37
+ // let variable = 'wave.direction.mean';
38
+
39
+ // let datasetName = 'obs-radar.rain.nzl.national';
40
+ // let variable = 'reflectivity';
41
+
42
+ // get datasetName from URL
43
+ const urlParams = window.location.toString().split('##')[1];
44
+ const params = urlParams?.split('/');
45
+ datasetName = params?.[0] || datasetName;
46
+ if (params?.[1]) variable = params[1];
47
+ let time = params?.[2] || '';
48
+ const zoom = (params && parseFloat(params[3])) || 0;
49
+ const lng = (params && parseFloat(params[4])) || 0;
50
+ const lat = (params && parseFloat(params[5])) || 0;
51
+ const bearing = (params && parseFloat(params[6])) || 0;
52
+ const pitch = (params && parseFloat(params[7])) || 0;
53
+ if (params?.length > 8) params[8] = params.slice(8).join('/');
54
+
55
+ const str = params?.[8] && params[8];
56
+ const sth = { style: {} as WxColorStyleWeak };
57
+ try {
58
+ // get style from URL
59
+ sth.style = str && { ...JSON.parse(decodeURI(str)) }; // reset levels if change units
60
+ } catch (e) {
61
+ /* ignore errors silently */
62
+ console.log(e);
63
+ }
64
+
65
+ params && flyTo(map, zoom, lng, lat, bearing, pitch); // if no params stay at default position set in initFrameWork()
66
+
67
+ // const sth = { style: {} };
68
+ map.on('zoom', () => setURL(map, time, datasetName, variable, sth.style));
69
+ map.on('drag', () => setURL(map, time, datasetName, variable, sth.style));
70
+ map.on('rotate', () => setURL(map, time, datasetName, variable, sth.style));
71
+ map.on('pitch', () => setURL(map, time, datasetName, variable, sth.style));
72
+
73
+ let wxsource: WxTileSource | undefined;
74
+
75
+ const legendControl = new WxLegendControl();
76
+ addControl(map, legendControl, 'top-right');
77
+
78
+ const frameworkOptions = { id: 'wxsource', opacity: OPACITY, attribution: 'WxTiles' };
79
+ const apiControl = new WxAPIControl(wxapi, datasetName, variable);
80
+ addControl(map, apiControl, 'top-left');
81
+ apiControl.onchange = async (datasetName_, variable_, nonnativecall): Promise<void> => {
82
+ WXLOG('apiControl.onchange datasetName=', datasetName_, 'variable=', variable_);
83
+ // remove existing source and layer
84
+ removeLayer(map, frameworkOptions.id, wxsource);
85
+ //
86
+ nonnativecall || (sth.style = {}); // reset style if change dataset/variable
87
+ wxsource = undefined;
88
+ datasetName = datasetName_;
89
+ variable = variable_;
90
+ const wxdatasetManager = await wxapi.createDatasetManager(datasetName);
91
+ const boundaries = wxdatasetManager.getBoundaries();
92
+ if (boundaries && !nonnativecall) {
93
+ const { east, west, north, south } = boundaries.boundariesnorm;
94
+ const zoom = Math.round(Math.log((360 * 360) / Math.max((east - west + 360) % 360, north - south) / 360) / Math.LN2); // from https://stackoverflow.com/questions/6048975/google-maps-v3-how-to-calculate-the-zoom-level-for-a-given-bounds
95
+ flyTo(map, zoom, (east + west) / 2, (north + south) / 2, 0, 0);
96
+ }
97
+ const meta = wxdatasetManager.getVariableMeta(variable);
98
+ if (meta?.units === 'RGB') {
99
+ addRaster(map, frameworkOptions.id, 'wxtiles', wxdatasetManager.createURI(variable, 0), wxdatasetManager.getMaxZoom());
100
+ timeControl.setTimes(wxdatasetManager.getTimes());
101
+ legendControl.clear();
102
+ } else {
103
+ wxsource = wxdatasetManager.createSourceLayer({ variable, time, wxstyle: sth.style }, frameworkOptions);
104
+ await addLayer(map, frameworkOptions.id, 'wxtiles', wxsource);
105
+ const styleCopy = wxsource.getCurrentStyleObjectCopy();
106
+ legendControl.drawLegend(styleCopy); // first draw legend with current style
107
+ styleCopy.levels = sth.style?.levels; // no need to show defaults it in the editor and URL
108
+ styleCopy.colors = sth.style?.colors; // no need to show defaults it in the editor and URL
109
+ await customStyleEditorControl.onchange?.(styleCopy, true);
110
+ }
111
+
112
+ timeControl.updateSource(wxsource);
113
+ };
114
+
115
+ const timeControl = new WxTimeControl(50);
116
+ addControl(map, timeControl, 'top-left');
117
+ timeControl.onchange = (time_) => {
118
+ setURL(map, (time = time_), datasetName, variable, sth.style);
119
+ };
120
+
121
+ const customStyleEditorControl = new WxStyleEditorControl();
122
+ addControl(map, customStyleEditorControl, 'top-right');
123
+ customStyleEditorControl.onchange = async (style, nonnativecall) => {
124
+ WXLOG('customStyleEditorControl.onchange');
125
+ if (!wxsource) return;
126
+ nonnativecall || (await wxsource.updateCurrentStyleObject(style)); // if called manually, do not update wxsource's style
127
+ const nstyle = wxsource.getCurrentStyleObjectCopy();
128
+ legendControl.drawLegend(nstyle);
129
+ nstyle.levels = style?.levels; // keep levels empty if they are not defined
130
+ nstyle.colors = style?.colors; // keep colors empty if they are not defined
131
+ customStyleEditorControl.setStyle(nstyle); // if called from wxsource, update customStyleEditorControl
132
+ sth.style = nstyle;
133
+ setURL(map, time, datasetName, variable, sth.style);
134
+ };
135
+
136
+ const infoControl = new WxInfoControl();
137
+ addControl(map, infoControl, 'bottom-left');
138
+ map.on('mousemove', (e) => infoControl.update(wxsource, map, position(e)));
139
+
140
+ await apiControl.onchange(datasetName, variable, true); // initial load
141
+
142
+ /*/ DEMO: more interactive - additional level and a bit of the red transparentness around the level made from current mouse position
143
+ if (wxsource) {
144
+ let busy = false;
145
+ await wxsource.updateCurrentStyleObject({ levels: undefined }); // await always !!
146
+ const levels = wxsource.getCurrentStyleObjectCopy().levels || []; // get current/default/any levels
147
+ const colMap: [number, string][] = levels.map((level) => [level, '#' + Math.random().toString(16).slice(2, 8) + 'ff']);
148
+ map.on('mousemove', async (e) => {
149
+ if (!wxsource || busy) return;
150
+ busy = true;
151
+ const tileInfo: WxTileInfo | undefined = wxsource.getLayerInfoAtLatLon(position(e), map);
152
+ if (tileInfo) {
153
+ await customStyleEditorControl.onchange?.({ colorMap: [...colMap, [tileInfo.inStyleUnits[0], '#ff000000']] }); // await always !!
154
+ }
155
+ busy = false;
156
+ });
157
+ } //*/
158
+
159
+ /*/ DEMO: abort
160
+ if (wxsource) {
161
+ const abortController = new AbortController();
162
+ console.log('setTime(5)');
163
+ const prom = wxsource.setTime(5, abortController);
164
+ abortController.abort(); // aborts the request
165
+ await prom; // await always !! even if aborted
166
+ console.log('aborted');
167
+ await wxsource.setTime(5); // no abort
168
+ console.log('setTime(5) done');
169
+ }//*/
170
+
171
+ /*/ DEMO: preload a timestep
172
+ map.once('click', async () => {
173
+ if (!wxsource) return;
174
+ console.log('no preload time=5');
175
+ const t = Date.now();
176
+ await wxsource.setTime(5); // await always !! or abort
177
+ console.log(Date.now() - t);
178
+ await wxsource.preloadTime(10); // await always !! even if aborted
179
+ await wxsource.preloadTime(20); // await always !! even if aborted
180
+ console.log('preloaded timesteps 10, 20');
181
+ map.once('click', async () => {
182
+ if (!wxsource) return;
183
+ const t = Date.now();
184
+ await wxsource.setTime(10); // await always !! or abort
185
+ console.log(Date.now() - t, ' step 10');
186
+ map.once('click', async () => {
187
+ if (!wxsource) return;
188
+ const t = Date.now();
189
+ await wxsource.setTime(20); // await always !! or abort
190
+ console.log(Date.now() - t, ' step 20');
191
+ });
192
+ });
193
+ }); //*/
194
+
195
+ /*/ DEMO: change style's units
196
+ let i = 0;
197
+ map.on('click', async () => {
198
+ if (!wxsource) return;
199
+ const u = ['knots', 'm/s', 'km/h', 'miles/h'];
200
+ await wxsource.updateCurrentStyleObject({ units: u[i], levels: undefined }); // levels: undefined - to recalculate levels
201
+ legendControl.drawLegend(wxsource.getCurrentStyleObjectCopy());
202
+ i = (i + 1) % u.length;
203
+ }); //*/
204
+
205
+ /*/ DEMO : read lon lat data
206
+ map.on('mousemove', (e) => {
207
+ if (!wxsource) return;
208
+ const pos = position(e); //
209
+ const tileInfo: WxTileInfo | undefined = wxsource.getLayerInfoAtLatLon(pos.wrap(), map);
210
+ if (tileInfo) {
211
+ console.log(tileInfo);
212
+ }
213
+ }); //*/
214
+
215
+ /*/ DEMO: timesteps
216
+ let t = 0;
217
+ const nextTimeStep = async () => {
218
+ if (!wxsource) return;
219
+ await wxsource.setTime(t++ % wxsource.wxdatasetManager.getTimes().length); // await always !!
220
+ setTimeout(nextTimeStep, 0);
221
+ };
222
+ setTimeout(nextTimeStep, 2000);
223
+ //*/
224
+
225
+ /*/ DEMO: Dynamic blur effect /
226
+ wxsource &&
227
+ (async function step(n: number = 0) {
228
+ await wxsource.updateCurrentStyleObject({ isolineText: false, blurRadius: ~~(10 * Math.sin(n / 500) + 10) }); // await always !!
229
+ requestAnimationFrame(step);
230
+ })();
231
+ //*/
232
+ }