@metoceanapi/wxtiles-leaflet 2.0.0 → 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.
@@ -4,19 +4,21 @@ import L from 'leaflet'; // goes first always!
4
4
  import { WxTileSource, type WxVars, WxAPI, WxTilesLogging, type WxTileInfo } from '../src/index';
5
5
  import { WxLegendControl } from '../src/controls/WxLegendControl';
6
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';
7
10
 
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,
15
- });
11
+ start();
12
+ // simpleDemo();
16
13
 
17
- L.control.zoom({ position: 'bottomright' }).addTo(map);
14
+ const OPACITY = 1;
18
15
 
19
- //******* WxTiles stuff *******//
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);
20
22
  WxTilesLogging(false);
21
23
  // const dataServerURL = 'http://localhost:9191/data/';
22
24
  const dataServerURL = 'https://tiles.metoceanapi.com/data/';
@@ -25,79 +27,118 @@ async function start() {
25
27
  // myHeaders.append('x-api-key', 'SpV3J1RypVrv2qkcJE91gG');
26
28
  const wxapi = new WxAPI({ dataServerURL, maskURL: 'none', qtreeURL: 'none', requestInit: { headers: myHeaders } });
27
29
 
28
- // const datasetName = 'wrf-ecmwf.gbr.national'; /* 'mercator.global/'; */ /* 'ecwmf.global/'; */ /* 'obs-radar.rain.nzl.national/'; */
29
- // const variables: WxVars = ['air.temperature.at-2m'];
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'];
30
33
 
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'];
34
+ let datasetName = 'ww3-ecmwf.global';
35
+ let variables: WxVars = ['wave.direction.mean'];
34
36
 
35
- // const datasetName = 'ww3-ecmwf.global';
36
- // const variables: WxVars = ['wave.direction.mean'];
37
+ // let datasetName = 'obs-radar.rain.nzl.national';
38
+ // let variables: WxVars = ['reflectivity'];
37
39
 
38
- // const datasetName = 'obs-radar.rain.nzl.national';
39
- // const variables: WxVars = ['reflectivity'];
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);
40
52
 
41
- const wxdatasetManager = await wxapi.createDatasetManager(datasetName);
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));
42
57
 
43
- const wxsource = new WxTileSource(
44
- {
45
- wxdatasetManager,
46
- variables,
47
- },
48
- {
49
- opacity: 0.5,
50
- attribution: 'WxTiles',
51
- }
52
- );
58
+ const frameworkOptions = { id: 'wxsource', opacity: OPACITY, attribution: 'WxTiles' };
53
59
 
54
- wxsource.addTo(map);
55
- await new Promise((done) => wxsource.once('load', done)); // highly recommended to await for the first load
60
+ let wxsource: WxTileSource | undefined;
56
61
 
57
62
  const legendControl = new WxLegendControl();
58
- map.addControl(new (L.Control.extend(legendControl.extender()))({ position: 'topright' }));
63
+ addControl(map, legendControl, 'top-right');
64
+
65
+ const apiControl = new WxAPIControl(wxapi, datasetName, variables[0]);
66
+ addControl(map, apiControl, 'top-left');
59
67
 
60
- const editor = new WxStyleEditorControl();
61
- map.addControl(new (L.Control.extend(editor.extender()))({ position: 'topleft' }));
68
+ const timeControl = new WxTimeControl(10);
69
+ addControl(map, timeControl, 'top-left');
70
+ timeControl.onchange = (time_) => setURL(map, (time = time_), datasetName, variables);
62
71
 
63
- const styleChanged = (editor.onchange = async (style) => {
72
+ const customStyleEditorControl = new WxStyleEditorControl();
73
+ addControl(map, customStyleEditorControl, 'top-left');
74
+ customStyleEditorControl.onchange = async (style) => {
75
+ if (!wxsource) return;
64
76
  await wxsource.updateCurrentStyleObject(style);
65
77
  const nstyle = wxsource.getCurrentStyleObjectCopy();
66
78
  legendControl.drawLegend(nstyle);
67
- editor.setStyle(nstyle);
68
- });
79
+ customStyleEditorControl.setStyle(nstyle);
80
+ };
69
81
 
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 !!
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);
85
105
  }
86
- busy = false;
87
- }); //*/
106
+ };
107
+
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
+ } //*/
88
126
 
89
127
  /*/ 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'); //*/
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
+ }//*/
98
138
 
99
139
  /*/ DEMO: preload a timestep
100
140
  map.once('click', async () => {
141
+ if (!wxsource) return;
101
142
  console.log('no preload time=5');
102
143
  const t = Date.now();
103
144
  await wxsource.setTime(5); // await always !! or abort
@@ -106,10 +147,12 @@ async function start() {
106
147
  await wxsource.preloadTime(20); // await always !! even if aborted
107
148
  console.log('preloaded timesteps 10, 20');
108
149
  map.once('click', async () => {
150
+ if (!wxsource) return;
109
151
  const t = Date.now();
110
152
  await wxsource.setTime(10); // await always !! or abort
111
153
  console.log(Date.now() - t, ' step 10');
112
154
  map.once('click', async () => {
155
+ if (!wxsource) return;
113
156
  const t = Date.now();
114
157
  await wxsource.setTime(20); // await always !! or abort
115
158
  console.log(Date.now() - t, ' step 20');
@@ -120,37 +163,28 @@ async function start() {
120
163
  /*/ DEMO: change style's units
121
164
  let i = 0;
122
165
  map.on('click', async () => {
166
+ if (!wxsource) return;
123
167
  const u = ['knots', 'm/s', 'km/h', 'miles/h'];
124
168
  await wxsource.updateCurrentStyleObject({ units: u[i], levels: undefined }); // levels: undefined - to recalculate levels
125
169
  legendControl.drawLegend(wxsource.getCurrentStyleObjectCopy());
126
170
  i = (i + 1) % u.length;
127
171
  }); //*/
128
172
 
129
- // DEMO (leaflet): read lon lat data
173
+ /*/ DEMO : read lon lat data
130
174
  map.on('mousemove', (e) => {
131
- const pos = e.latlng; // (leaflet)
175
+ if (!wxsource) return;
176
+ const pos = position(e); //
132
177
  const tileInfo: WxTileInfo | undefined = wxsource.getLayerInfoAtLatLon(pos.wrap(), map);
133
178
  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);
179
+ console.log(tileInfo);
146
180
  }
147
181
  }); //*/
148
182
 
149
183
  /*/ DEMO: timesteps
150
- const tlength = wxsource.wxdatasetManager.getTimes().length;
151
184
  let t = 0;
152
185
  const nextTimeStep = async () => {
153
- await wxsource.setTime(t++ % tlength); // await always !!
186
+ if (!wxsource) return;
187
+ await wxsource.setTime(t++ % wxsource.wxdatasetManager.getTimes().length); // await always !!
154
188
  setTimeout(nextTimeStep, 0);
155
189
  };
156
190
  setTimeout(nextTimeStep, 2000);
@@ -160,6 +194,7 @@ async function start() {
160
194
  let b = 0;
161
195
  let db = 1;
162
196
  const nextAnim = async () => {
197
+ if (!wxsource) return;
163
198
  await wxsource.updateCurrentStyleObject({ blurRadius: b }); // await always !!
164
199
 
165
200
  b += db;
@@ -169,4 +204,85 @@ async function start() {
169
204
  setTimeout(nextAnim, 2000); //*/
170
205
  }
171
206
 
172
- start();
207
+ function flyTo(map: L.Map, zoom: number, lng: number, lat: number, bearing: number, pitch: number) {
208
+ map.flyTo([lat, lng], zoom);
209
+ }
210
+
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)}`;
214
+ }
215
+
216
+ async function initFrameWork() {
217
+ const map = L.map('map', {
218
+ center: [-40.75, 174.5],
219
+ zoom: 3,
220
+ zoomControl: false,
221
+ });
222
+
223
+ L.control.zoom({ position: 'bottomright' }).addTo(map);
224
+ return map;
225
+ }
226
+
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 }));
230
+ }
231
+
232
+ function position(e: L.LeafletMouseEvent): L.LatLng {
233
+ return e.latlng.wrap(); // (mapbox)
234
+ }
235
+
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);
240
+ }
241
+ });
242
+ }
243
+
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
+ }
248
+
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);
252
+ }
253
+
254
+ async function simpleDemo() {
255
+ const map = L.map('map', { center: [0, 0], zoom: 2, zoomControl: true });
256
+
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
263
+
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 });
267
+
268
+ const datasetName = 'gfs.global';
269
+ const variable = 'air.temperature.at-2m'; // Scalar example
270
+ // const variable = 'wind.speed.eastward.at-10m'; // Vector example
271
+
272
+ // Create a dataset manager (may be used for many layers from this dataset)
273
+ const wxdatasetManager = await wxapi.createDatasetManager(datasetName);
274
+
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);
278
+
279
+ // create a layer
280
+ const leafletOptions: L.GridLayerOptions = { opacity: 1, attribution: 'WxTiles' };
281
+ const wxsource = new WxTileSource({ wxdatasetManager, variables }, leafletOptions);
282
+
283
+ // add the layer to the map
284
+ map.addLayer(wxsource);
285
+
286
+ // await for the first load
287
+ await new Promise((done) => wxsource.once('load', done)); // highly recommended to await for the first load
288
+ }