@metoceanapi/wxtiles-leaflet 1.1.2 → 2.0.4

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.
Files changed (40) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +2 -2
  3. package/build-for-docs.js +23 -0
  4. package/dist/es/controls/WxAPIControl.d.ts +17 -0
  5. package/dist/es/controls/WxInfoControl.d.ts +15 -0
  6. package/dist/es/controls/WxLegendControl.d.ts +14 -0
  7. package/dist/es/controls/WxStyleEditorControl.d.ts +47 -0
  8. package/dist/es/controls/WxTimeControl .d.ts +18 -0
  9. package/dist/es/defaults/colorschemes.d.ts +2 -2
  10. package/dist/{web/wxtiles.css → es/index.css} +1 -1
  11. package/dist/es/index.d.ts +8 -0
  12. package/dist/es/index.js +1 -0
  13. package/dist/es/utils/RawCLUT.d.ts +29 -8
  14. package/dist/es/utils/qtree.d.ts +13 -6
  15. package/dist/es/utils/wxtools.d.ts +41 -26
  16. package/dist/es/wxAPI/WxDataSetManager.d.ts +96 -0
  17. package/dist/es/wxAPI/wxAPI.d.ts +120 -0
  18. package/dist/es/wxlayer/WxImplementation.d.ts +116 -0
  19. package/dist/es/wxlayer/loader.d.ts +30 -0
  20. package/dist/es/wxlayer/loadertools.d.ts +12 -0
  21. package/dist/es/wxlayer/painter.d.ts +14 -0
  22. package/dist/es/wxlayer/wxlayer.d.ts +80 -0
  23. package/dist/es/wxsource/wxsource.d.ts +41 -0
  24. package/dist/es/wxsource/wxsourcetypes.d.ts +5 -0
  25. package/dist/{es/wxtiles.css → web/index.css} +1 -1
  26. package/dist/web/index.js +1 -0
  27. package/docs/index.css +10 -0
  28. package/docs/index.html +23 -0
  29. package/docs/res/icon.png +0 -0
  30. package/docs/res/wxtiles-logo.png +0 -0
  31. package/docs/script/script.css +1 -0
  32. package/docs/script/script.js +9 -0
  33. package/package.json +13 -10
  34. package/src_example/index.ts +252 -496
  35. package/dist/es/tile.d.ts +0 -57
  36. package/dist/es/tilesLayer.d.ts +0 -147
  37. package/dist/es/wxtiles.d.ts +0 -27
  38. package/dist/es/wxtiles.js +0 -1
  39. package/dist/web/wxtiles.js +0 -1
  40. package/src_example/visualStyleEditor.ts +0 -326
@@ -1,532 +1,288 @@
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';
20
-
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
- }
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';
7
+ import { WxInfoControl } from '../src/controls/WxInfoControl';
8
+ import { WxTimeControl } from '../src/controls/WxTimeControl ';
9
+ import { WxAPIControl } from '../src/controls/WxAPIControl';
75
10
 
76
- if (meta.variables.includes(oldVariable)) {
77
- selectVariableEl.value = oldVariable;
78
- }
11
+ start();
12
+ // simpleDemo();
79
13
 
80
- defaultVariable && meta.variables.find((n) => n === defaultVariable) && (selectVariableEl.value = defaultVariable);
14
+ const OPACITY = 1;
81
15
 
82
- await loadVariable_selectVariableEl_onchange();
83
- }
16
+ // this is universal function for Leaflet and Mapbox.
17
+ // Functions below are just framework specific wrappers for this universal function
18
+ // start() is the fully interchangable function for Leaflet and Mapbox
19
+ async function start() {
20
+ const map = await initFrameWork();
21
+ addRaster(map, 'baseS', 'baseL', 'https://tiles.metoceanapi.com/base-lines/{z}/{x}/{y}', 5);
22
+ WxTilesLogging(false);
23
+ // const dataServerURL = 'http://localhost:9191/data/';
24
+ const dataServerURL = 'https://tiles.metoceanapi.com/data/';
25
+ // const dataServerURL = 'http://tiles3.metoceanapi.com/';
26
+ const myHeaders = new Headers();
27
+ // myHeaders.append('x-api-key', 'SpV3J1RypVrv2qkcJE91gG');
28
+ const wxapi = new WxAPI({ dataServerURL, maskURL: 'none', qtreeURL: 'none', requestInit: { headers: myHeaders } });
29
+
30
+ // let datasetName = 'gfs.global'; /* 'mercator.global/'; */ /* 'ecwmf.global/'; */ /* 'obs-radar.rain.nzl.national/'; */
31
+ // let variables: WxVars = ['air.temperature.at-2m'];
32
+ // let variables: WxVars = ['wind.speed.eastward.at-10m', 'wind.speed.northward.at-10m'];
33
+
34
+ let datasetName = 'ww3-ecmwf.global';
35
+ let variables: WxVars = ['wave.direction.mean'];
36
+
37
+ // let datasetName = 'obs-radar.rain.nzl.national';
38
+ // let variables: WxVars = ['reflectivity'];
39
+
40
+ // get datasetName from URL
41
+ const urlParams = window.location.toString().split('#')[1];
42
+ const params = urlParams?.split('/');
43
+ datasetName = params?.[0] || datasetName;
44
+ if (params?.[1]) variables = params[1].split(',') as WxVars;
45
+ let time = params?.[2] || '';
46
+ const zoom = (params && parseFloat(params[3])) || 0;
47
+ const lng = (params && parseFloat(params[4])) || 0;
48
+ const lat = (params && parseFloat(params[5])) || 0;
49
+ const bearing = (params && parseFloat(params[6])) || 0;
50
+ const pitch = (params && parseFloat(params[3])) || 0;
51
+ flyTo(map, zoom, lng, lat, bearing, pitch);
52
+
53
+ map.on('zoom', () => setURL(map, time, datasetName, variables));
54
+ map.on('drag', () => setURL(map, time, datasetName, variables));
55
+ map.on('rotate', () => setURL(map, time, datasetName, variables));
56
+ map.on('pitch', () => setURL(map, time, datasetName, variables));
57
+
58
+ const frameworkOptions = { id: 'wxsource', opacity: OPACITY, attribution: 'WxTiles' };
59
+
60
+ let wxsource: WxTileSource | undefined;
61
+
62
+ const legendControl = new WxLegendControl();
63
+ addControl(map, legendControl, 'top-right');
64
+
65
+ const apiControl = new WxAPIControl(wxapi, datasetName, variables[0]);
66
+ addControl(map, apiControl, 'top-left');
67
+
68
+ const timeControl = new WxTimeControl(10);
69
+ addControl(map, timeControl, 'top-left');
70
+ timeControl.onchange = (time_) => setURL(map, (time = time_), datasetName, variables);
71
+
72
+ const customStyleEditorControl = new WxStyleEditorControl();
73
+ addControl(map, customStyleEditorControl, 'top-left');
74
+ customStyleEditorControl.onchange = async (style) => {
75
+ if (!wxsource) return;
76
+ await wxsource.updateCurrentStyleObject(style);
77
+ const nstyle = wxsource.getCurrentStyleObjectCopy();
78
+ legendControl.drawLegend(nstyle);
79
+ customStyleEditorControl.setStyle(nstyle);
80
+ };
84
81
 
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
- },
82
+ const infoControl = new WxInfoControl();
83
+ addControl(map, infoControl, 'bottom-left');
84
+ map.on('mousemove', (e) => infoControl.update(wxsource, map, position(e)));
85
+
86
+ apiControl.onchange = async (datasetName_: string, variable: string): Promise<void> => {
87
+ // remove existing source and layer
88
+ removeLayer(map, frameworkOptions.id, wxsource);
89
+ //
90
+ wxsource = undefined;
91
+ datasetName = datasetName_;
92
+ const wxdatasetManager = await wxapi.createDatasetManager(datasetName);
93
+ const meta = wxdatasetManager.getVariableMeta(variable);
94
+ variables = wxdatasetManager.checkCombineVariableIfVector(variable); // check if variable is vector and use vector components if so
95
+ if (meta?.units === 'RGB') {
96
+ addRaster(map, frameworkOptions.id, 'wxtiles', wxdatasetManager.createURI(variables[0], 0), wxdatasetManager.getMaxZoom());
97
+ timeControl.setTimes(wxdatasetManager.getTimes());
98
+ legendControl.clear();
99
+ } else {
100
+ wxsource = new WxTileSource({ wxdatasetManager, variables }, frameworkOptions);
101
+ await addLayer(map, frameworkOptions.id, 'wxtiles', wxsource);
102
+ await customStyleEditorControl.onchange?.(wxsource.getCurrentStyleObjectCopy());
103
+ legendControl.drawLegend(wxsource.getCurrentStyleObjectCopy());
104
+ timeControl.updateSource(wxsource);
105
+ }
114
106
  };
115
107
 
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
108
+ await apiControl.onchange(datasetName, variables[0]); // initial load
109
+
110
+ /*/ DEMO: more interactive - additional level and a bit of the red transparentness around the level made from current mouse position6
111
+ if (wxsource) {
112
+ let busy = false;
113
+ await wxsource.updateCurrentStyleObject({ levels: undefined }); // await always !!
114
+ const levels = wxsource.getCurrentStyleObjectCopy().levels || []; // get current/default/any levels
115
+ const colMap: [number, string][] = levels.map((level) => [level, '#' + Math.random().toString(16).slice(2, 8) + 'ff']);
116
+ map.on('mousemove', async (e) => {
117
+ if (!wxsource || busy) return;
118
+ busy = true;
119
+ const tileInfo: WxTileInfo | undefined = wxsource.getLayerInfoAtLatLon(position(e), map);
120
+ if (tileInfo) {
121
+ await customStyleEditorControl.onchange?.({ colorMap: [...colMap, [tileInfo.inStyleUnits[0], '#ff000000']] }); // await always !!
122
+ }
123
+ busy = false;
124
+ });
125
+ } //*/
126
+
127
+ /*/ DEMO: abort
128
+ if (wxsource) {
129
+ const abortController = new AbortController();
130
+ console.log('setTime(5)');
131
+ const prom = wxsource.setTime(5, abortController);
132
+ abortController.abort(); // aborts the request
133
+ await prom; // await always !! even if aborted
134
+ console.log('aborted');
135
+ await wxsource.setTime(5); // no abort
136
+ console.log('setTime(5) done');
137
+ }//*/
138
+
139
+ /*/ DEMO: preload a timestep
140
+ map.once('click', async () => {
141
+ if (!wxsource) return;
142
+ console.log('no preload time=5');
143
+ const t = Date.now();
144
+ await wxsource.setTime(5); // await always !! or abort
145
+ console.log(Date.now() - t);
146
+ await wxsource.preloadTime(10); // await always !! even if aborted
147
+ await wxsource.preloadTime(20); // await always !! even if aborted
148
+ console.log('preloaded timesteps 10, 20');
149
+ map.once('click', async () => {
150
+ if (!wxsource) return;
151
+ const t = Date.now();
152
+ await wxsource.setTime(10); // await always !! or abort
153
+ console.log(Date.now() - t, ' step 10');
154
+ map.once('click', async () => {
155
+ if (!wxsource) return;
156
+ const t = Date.now();
157
+ await wxsource.setTime(20); // await always !! or abort
158
+ console.log(Date.now() - t, ' step 20');
159
+ });
160
+ });
161
+ }); //*/
162
+
163
+ /*/ DEMO: change style's units
164
+ let i = 0;
165
+ map.on('click', async () => {
166
+ if (!wxsource) return;
167
+ const u = ['knots', 'm/s', 'km/h', 'miles/h'];
168
+ await wxsource.updateCurrentStyleObject({ units: u[i], levels: undefined }); // levels: undefined - to recalculate levels
169
+ legendControl.drawLegend(wxsource.getCurrentStyleObjectCopy());
170
+ i = (i + 1) % u.length;
171
+ }); //*/
172
+
173
+ /*/ DEMO : read lon lat data
174
+ map.on('mousemove', (e) => {
175
+ if (!wxsource) return;
176
+ const pos = position(e); //
177
+ const tileInfo: WxTileInfo | undefined = wxsource.getLayerInfoAtLatLon(pos.wrap(), map);
178
+ if (tileInfo) {
179
+ console.log(tileInfo);
180
+ }
181
+ }); //*/
182
+
183
+ /*/ DEMO: timesteps
184
+ let t = 0;
185
+ const nextTimeStep = async () => {
186
+ if (!wxsource) return;
187
+ await wxsource.setTime(t++ % wxsource.wxdatasetManager.getTimes().length); // await always !!
188
+ setTimeout(nextTimeStep, 0);
189
+ };
190
+ setTimeout(nextTimeStep, 2000);
191
+ //*/
192
+
193
+ /*/ DEMO: Dynamic blur effect /
194
+ let b = 0;
195
+ let db = 1;
196
+ const nextAnim = async () => {
197
+ if (!wxsource) return;
198
+ await wxsource.updateCurrentStyleObject({ blurRadius: b }); // await always !!
199
+
200
+ b += db;
201
+ if (b > 16 || b < 0) db = -db;
202
+ setTimeout(nextAnim, 1);
203
+ };
204
+ setTimeout(nextAnim, 2000); //*/
131
205
  }
132
206
 
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);
142
- });
143
-
144
- selectTimeEl.value = layer.getTime();
207
+ function flyTo(map: L.Map, zoom: number, lng: number, lat: number, bearing: number, pitch: number) {
208
+ map.flyTo([lat, lng], zoom);
145
209
  }
146
210
 
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
- })();
211
+ function setURL(map: L.Map, time: string, datasetName: string, variables: string[]) {
212
+ const center = map.getCenter();
213
+ location.href = `#${datasetName}/${variables.join(',')}/${time}/${map.getZoom().toFixed(2)}/${center.lng.toFixed(2)}/${center.lat.toFixed(2)}`;
165
214
  }
166
215
 
167
- async function stopPlay() {
168
- if (buttonPlayStopEl.textContent !== 'play') {
169
- buttonPlayStopEl.textContent = 'play';
170
- return globalLayer?.unsetTimeAnimationMode();
171
- }
216
+ async function initFrameWork() {
217
+ const map = L.map('map', {
218
+ center: [-40.75, 174.5],
219
+ zoom: 3,
220
+ zoomControl: false,
221
+ });
172
222
 
173
- return;
223
+ L.control.zoom({ position: 'bottomright' }).addTo(map);
224
+ return map;
174
225
  }
175
226
 
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);
227
+ function addControl(map: L.Map, control: { extender: () => any }, position: string) {
228
+ position = position.replace('-', '');
229
+ map.addControl(new (L.Control.extend(control.extender()))({ position: position as any }));
181
230
  }
182
231
 
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();
232
+ function position(e: L.LeafletMouseEvent): L.LatLng {
233
+ return e.latlng.wrap(); // (mapbox)
197
234
  }
198
235
 
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;
236
+ function removeLayer(map: L.Map, layerId: string, layer?: L.Layer) {
237
+ map.eachLayer((l: any) => {
238
+ if (l.options.id === layerId) {
239
+ map.removeLayer(l);
213
240
  }
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 });
241
+ });
224
242
  }
225
243
 
226
- function drawLegend({ legend, canvas }: { legend: Legend; canvas: HTMLCanvasElement }) {
227
- if (!globalLayer || !canvas || !legend) return;
228
-
229
- const { width, height } = canvas;
230
- const halfHeight = (16 + height) >> 2;
231
-
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);
237
-
238
- const startX = 2;
239
- const startY = 2;
240
- const startXY = startX + width * startY;
241
-
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
- }
244
+ async function addLayer(map: L.Map, idS: string, idL: string, layer: L.Layer) {
245
+ map.addLayer(layer);
246
+ await new Promise((done) => layer.once('load', done)); // highly recommended to await for the first load
247
+ }
255
248
 
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
- }
263
-
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
- }
274
- }
275
- }
276
-
277
- ctx.putImageData(imData, 0, 0);
278
-
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
- }
288
-
289
- ctx.font = '12px sans-serif';
290
- const txt = `${globalLayer.getStyle().name} (${legend.units})`;
291
- ctx.fillText(txt, 13, height - 5);
292
- ctx.stroke();
293
-
294
- ctx.strokeStyle = '#888';
295
- ctx.strokeRect(1, 1, width - 3, height - 2); //for white background
249
+ function addRaster(map: L.Map, idS: string, idL: string, URL: string, maxZoom: number) {
250
+ const layer = L.tileLayer(URL, { id: idS, maxNativeZoom: maxZoom, zIndex: idL === 'baseL' ? 100 : 0 });
251
+ map.addLayer(layer);
296
252
  }
297
253
 
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
- }
316
- });
254
+ async function simpleDemo() {
255
+ const map = L.map('map', { center: [0, 0], zoom: 2, zoomControl: true });
317
256
 
318
- infoPanelEl.innerHTML = content;
319
- }
257
+ const dataServerURL = 'https://tiles.metoceanapi.com/data/';
258
+ // const headers = new Headers();
259
+ // headers.append('x-api-key', '--proper-key-value--'); // If needed in the future
260
+ const requestInit: RequestInit = {
261
+ /* headers */
262
+ }; // add more options if needed such as headers, mode, credentials, etc
320
263
 
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>
339
- }
340
- });
264
+ // Get the API ready - should be ONE per application
265
+ WxTilesLogging(true); // If needed
266
+ const wxapi = new WxAPI({ dataServerURL, maskURL: 'none', qtreeURL: 'none', requestInit });
341
267
 
342
- L.popup()
343
- .setLatLng(e.latlng)
344
- .setContent(content + `${e.latlng}`)
345
- .openOn(map);
346
- }
268
+ const datasetName = 'gfs.global';
269
+ const variable = 'air.temperature.at-2m'; // Scalar example
270
+ // const variable = 'wind.speed.eastward.at-10m'; // Vector example
347
271
 
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
- }
272
+ // Create a dataset manager (may be used for many layers from this dataset)
273
+ const wxdatasetManager = await wxapi.createDatasetManager(datasetName);
355
274
 
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
- }
275
+ // Usefull to automatically get the vector component variables from the dataset manager if given variable is northward or eastward
276
+ // if not a vector component, then just return the variable itself
277
+ const variables = wxdatasetManager.checkCombineVariableIfVector(variable);
369
278
 
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();
444
- };
445
- }
279
+ // create a layer
280
+ const leafletOptions: L.GridLayerOptions = { opacity: 1, attribution: 'WxTiles' };
281
+ const wxsource = new WxTileSource({ wxdatasetManager, variables }, leafletOptions);
446
282
 
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
- });
283
+ // add the layer to the map
284
+ map.addLayer(wxsource);
531
285
 
532
- start();
286
+ // await for the first load
287
+ await new Promise((done) => wxsource.once('load', done)); // highly recommended to await for the first load
288
+ }