@metoceanapi/wxtiles-leaflet 2.0.0 → 2.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,100 +4,146 @@ 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/';
23
25
  // const dataServerURL = 'http://tiles3.metoceanapi.com/';
24
26
  const myHeaders = new Headers();
25
27
  // myHeaders.append('x-api-key', 'SpV3J1RypVrv2qkcJE91gG');
26
- const wxapi = new WxAPI({ dataServerURL, maskURL: 'none', qtreeURL: 'none', requestInit: { headers: myHeaders } });
28
+ const wxapi = new WxAPI({
29
+ dataServerURL,
30
+ maskURL: dataServerURL + 'masks/{z}/{x}/{y}.png',
31
+ qtreeURL: dataServerURL + 'masks/9+1.seamask.qtree',
32
+ requestInit: { headers: myHeaders },
33
+ });
27
34
 
28
- // const datasetName = 'wrf-ecmwf.gbr.national'; /* 'mercator.global/'; */ /* 'ecwmf.global/'; */ /* 'obs-radar.rain.nzl.national/'; */
29
- // const variables: WxVars = ['air.temperature.at-2m'];
35
+ let datasetName = 'gfs.global'; /* 'mercator.global/'; */ /* 'ecwmf.global/'; */ /* 'obs-radar.rain.nzl.national/'; */
36
+ let variables: WxVars = ['air.temperature.at-2m'];
37
+ // let variables: WxVars = ['wind.speed.eastward.at-10m', 'wind.speed.northward.at-10m'];
30
38
 
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'];
39
+ // let datasetName = 'ww3-ecmwf.global';
40
+ // let variables: WxVars = ['wave.direction.mean'];
34
41
 
35
- // const datasetName = 'ww3-ecmwf.global';
36
- // const variables: WxVars = ['wave.direction.mean'];
42
+ // let datasetName = 'obs-radar.rain.nzl.national';
43
+ // let variables: WxVars = ['reflectivity'];
37
44
 
38
- // const datasetName = 'obs-radar.rain.nzl.national';
39
- // const variables: WxVars = ['reflectivity'];
45
+ // get datasetName from URL
46
+ const urlParams = window.location.toString().split('#')[1];
47
+ const params = urlParams?.split('/');
48
+ datasetName = params?.[0] || datasetName;
49
+ if (params?.[1]) variables = params[1].split(',') as WxVars;
50
+ let time = params?.[2] || '';
51
+ const zoom = (params && parseFloat(params[3])) || 0;
52
+ const lng = (params && parseFloat(params[4])) || 0;
53
+ const lat = (params && parseFloat(params[5])) || 0;
54
+ const bearing = (params && parseFloat(params[6])) || 0;
55
+ const pitch = (params && parseFloat(params[3])) || 0;
56
+ flyTo(map, zoom, lng, lat, bearing, pitch);
40
57
 
41
- const wxdatasetManager = await wxapi.createDatasetManager(datasetName);
58
+ map.on('zoom', () => setURL(map, time, datasetName, variables));
59
+ map.on('drag', () => setURL(map, time, datasetName, variables));
60
+ map.on('rotate', () => setURL(map, time, datasetName, variables));
61
+ map.on('pitch', () => setURL(map, time, datasetName, variables));
42
62
 
43
- const wxsource = new WxTileSource(
44
- {
45
- wxdatasetManager,
46
- variables,
47
- },
48
- {
49
- opacity: 0.5,
50
- attribution: 'WxTiles',
51
- }
52
- );
63
+ const frameworkOptions = { id: 'wxsource', opacity: OPACITY, attribution: 'WxTiles' };
53
64
 
54
- wxsource.addTo(map);
55
- await new Promise((done) => wxsource.once('load', done)); // highly recommended to await for the first load
65
+ let wxsource: WxTileSource | undefined;
56
66
 
57
67
  const legendControl = new WxLegendControl();
58
- map.addControl(new (L.Control.extend(legendControl.extender()))({ position: 'topright' }));
68
+ addControl(map, legendControl, 'top-right');
59
69
 
60
- const editor = new WxStyleEditorControl();
61
- map.addControl(new (L.Control.extend(editor.extender()))({ position: 'topleft' }));
70
+ const apiControl = new WxAPIControl(wxapi, datasetName, variables[0]);
71
+ addControl(map, apiControl, 'top-left');
62
72
 
63
- const styleChanged = (editor.onchange = async (style) => {
73
+ const timeControl = new WxTimeControl(10);
74
+ addControl(map, timeControl, 'top-left');
75
+ timeControl.onchange = (time_) => setURL(map, (time = time_), datasetName, variables);
76
+
77
+ const customStyleEditorControl = new WxStyleEditorControl();
78
+ addControl(map, customStyleEditorControl, 'top-left');
79
+ customStyleEditorControl.onchange = async (style) => {
80
+ if (!wxsource) return;
64
81
  await wxsource.updateCurrentStyleObject(style);
65
82
  const nstyle = wxsource.getCurrentStyleObjectCopy();
66
83
  legendControl.drawLegend(nstyle);
67
- editor.setStyle(nstyle);
68
- });
84
+ customStyleEditorControl.setStyle(nstyle);
85
+ };
69
86
 
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 !!
87
+ const infoControl = new WxInfoControl();
88
+ addControl(map, infoControl, 'bottom-left');
89
+ map.on('mousemove', (e) => infoControl.update(wxsource, map, position(e)));
90
+
91
+ apiControl.onchange = async (datasetName_: string, variable: string): Promise<void> => {
92
+ // remove existing source and layer
93
+ removeLayer(map, frameworkOptions.id, wxsource);
94
+ //
95
+ wxsource = undefined;
96
+ datasetName = datasetName_;
97
+ const wxdatasetManager = await wxapi.createDatasetManager(datasetName);
98
+ const meta = wxdatasetManager.getVariableMeta(variable);
99
+ variables = wxdatasetManager.checkCombineVariableIfVector(variable); // check if variable is vector and use vector components if so
100
+ if (meta?.units === 'RGB') {
101
+ addRaster(map, frameworkOptions.id, 'wxtiles', wxdatasetManager.createURI(variables[0], 0), wxdatasetManager.getMaxZoom());
102
+ timeControl.setTimes(wxdatasetManager.getTimes());
103
+ legendControl.clear();
104
+ } else {
105
+ wxsource = new WxTileSource({ wxdatasetManager, variables }, frameworkOptions);
106
+ await addLayer(map, frameworkOptions.id, 'wxtiles', wxsource);
107
+ await customStyleEditorControl.onchange?.(wxsource.getCurrentStyleObjectCopy());
108
+ legendControl.drawLegend(wxsource.getCurrentStyleObjectCopy());
109
+ timeControl.updateSource(wxsource);
85
110
  }
86
- busy = false;
87
- }); //*/
111
+ };
112
+
113
+ await apiControl.onchange(datasetName, variables[0]); // initial load
114
+
115
+ /*/ DEMO: more interactive - additional level and a bit of the red transparentness around the level made from current mouse position6
116
+ if (wxsource) {
117
+ let busy = false;
118
+ await wxsource.updateCurrentStyleObject({ levels: undefined }); // await always !!
119
+ const levels = wxsource.getCurrentStyleObjectCopy().levels || []; // get current/default/any levels
120
+ const colMap: [number, string][] = levels.map((level) => [level, '#' + Math.random().toString(16).slice(2, 8) + 'ff']);
121
+ map.on('mousemove', async (e) => {
122
+ if (!wxsource || busy) return;
123
+ busy = true;
124
+ const tileInfo: WxTileInfo | undefined = wxsource.getLayerInfoAtLatLon(position(e), map);
125
+ if (tileInfo) {
126
+ await customStyleEditorControl.onchange?.({ colorMap: [...colMap, [tileInfo.inStyleUnits[0], '#ff000000']] }); // await always !!
127
+ }
128
+ busy = false;
129
+ });
130
+ } //*/
88
131
 
89
132
  /*/ 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'); //*/
133
+ if (wxsource) {
134
+ const abortController = new AbortController();
135
+ console.log('setTime(5)');
136
+ const prom = wxsource.setTime(5, abortController);
137
+ abortController.abort(); // aborts the request
138
+ await prom; // await always !! even if aborted
139
+ console.log('aborted');
140
+ await wxsource.setTime(5); // no abort
141
+ console.log('setTime(5) done');
142
+ }//*/
98
143
 
99
144
  /*/ DEMO: preload a timestep
100
145
  map.once('click', async () => {
146
+ if (!wxsource) return;
101
147
  console.log('no preload time=5');
102
148
  const t = Date.now();
103
149
  await wxsource.setTime(5); // await always !! or abort
@@ -106,10 +152,12 @@ async function start() {
106
152
  await wxsource.preloadTime(20); // await always !! even if aborted
107
153
  console.log('preloaded timesteps 10, 20');
108
154
  map.once('click', async () => {
155
+ if (!wxsource) return;
109
156
  const t = Date.now();
110
157
  await wxsource.setTime(10); // await always !! or abort
111
158
  console.log(Date.now() - t, ' step 10');
112
159
  map.once('click', async () => {
160
+ if (!wxsource) return;
113
161
  const t = Date.now();
114
162
  await wxsource.setTime(20); // await always !! or abort
115
163
  console.log(Date.now() - t, ' step 20');
@@ -120,37 +168,28 @@ async function start() {
120
168
  /*/ DEMO: change style's units
121
169
  let i = 0;
122
170
  map.on('click', async () => {
171
+ if (!wxsource) return;
123
172
  const u = ['knots', 'm/s', 'km/h', 'miles/h'];
124
173
  await wxsource.updateCurrentStyleObject({ units: u[i], levels: undefined }); // levels: undefined - to recalculate levels
125
174
  legendControl.drawLegend(wxsource.getCurrentStyleObjectCopy());
126
175
  i = (i + 1) % u.length;
127
176
  }); //*/
128
177
 
129
- // DEMO (leaflet): read lon lat data
178
+ /*/ DEMO : read lon lat data
130
179
  map.on('mousemove', (e) => {
131
- const pos = e.latlng; // (leaflet)
180
+ if (!wxsource) return;
181
+ const pos = position(e); //
132
182
  const tileInfo: WxTileInfo | undefined = wxsource.getLayerInfoAtLatLon(pos.wrap(), map);
133
183
  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);
184
+ console.log(tileInfo);
146
185
  }
147
186
  }); //*/
148
187
 
149
188
  /*/ DEMO: timesteps
150
- const tlength = wxsource.wxdatasetManager.getTimes().length;
151
189
  let t = 0;
152
190
  const nextTimeStep = async () => {
153
- await wxsource.setTime(t++ % tlength); // await always !!
191
+ if (!wxsource) return;
192
+ await wxsource.setTime(t++ % wxsource.wxdatasetManager.getTimes().length); // await always !!
154
193
  setTimeout(nextTimeStep, 0);
155
194
  };
156
195
  setTimeout(nextTimeStep, 2000);
@@ -160,6 +199,7 @@ async function start() {
160
199
  let b = 0;
161
200
  let db = 1;
162
201
  const nextAnim = async () => {
202
+ if (!wxsource) return;
163
203
  await wxsource.updateCurrentStyleObject({ blurRadius: b }); // await always !!
164
204
 
165
205
  b += db;
@@ -169,4 +209,85 @@ async function start() {
169
209
  setTimeout(nextAnim, 2000); //*/
170
210
  }
171
211
 
172
- start();
212
+ function flyTo(map: L.Map, zoom: number, lng: number, lat: number, bearing: number, pitch: number) {
213
+ map.flyTo([lat, lng], zoom);
214
+ }
215
+
216
+ function setURL(map: L.Map, time: string, datasetName: string, variables: string[]) {
217
+ const center = map.getCenter();
218
+ location.href = `#${datasetName}/${variables.join(',')}/${time}/${map.getZoom().toFixed(2)}/${center.lng.toFixed(2)}/${center.lat.toFixed(2)}`;
219
+ }
220
+
221
+ async function initFrameWork() {
222
+ const map = L.map('map', {
223
+ center: [-40.75, 174.5],
224
+ zoom: 3,
225
+ zoomControl: false,
226
+ });
227
+
228
+ L.control.zoom({ position: 'bottomright' }).addTo(map);
229
+ return map;
230
+ }
231
+
232
+ function addControl(map: L.Map, control: { extender: () => any }, position: string) {
233
+ position = position.replace('-', '');
234
+ map.addControl(new (L.Control.extend(control.extender()))({ position: position as any }));
235
+ }
236
+
237
+ function position(e: L.LeafletMouseEvent): L.LatLng {
238
+ return e.latlng.wrap(); // (mapbox)
239
+ }
240
+
241
+ function removeLayer(map: L.Map, layerId: string, layer?: L.Layer) {
242
+ map.eachLayer((l: any) => {
243
+ if (l.options.id === layerId) {
244
+ map.removeLayer(l);
245
+ }
246
+ });
247
+ }
248
+
249
+ async function addLayer(map: L.Map, idS: string, idL: string, layer: L.Layer) {
250
+ map.addLayer(layer);
251
+ await new Promise((done) => layer.once('load', done)); // highly recommended to await for the first load
252
+ }
253
+
254
+ function addRaster(map: L.Map, idS: string, idL: string, URL: string, maxZoom: number) {
255
+ const layer = L.tileLayer(URL, { id: idS, maxNativeZoom: maxZoom, zIndex: idL === 'baseL' ? 100 : 0 });
256
+ map.addLayer(layer);
257
+ }
258
+
259
+ async function simpleDemo() {
260
+ const map = L.map('map', { center: [0, 0], zoom: 2, zoomControl: true });
261
+
262
+ const dataServerURL = 'https://tiles.metoceanapi.com/data/';
263
+ // const headers = new Headers();
264
+ // headers.append('x-api-key', '--proper-key-value--'); // If needed in the future
265
+ const requestInit: RequestInit = {
266
+ /* headers */
267
+ }; // add more options if needed such as headers, mode, credentials, etc
268
+
269
+ // Get the API ready - should be ONE per application
270
+ WxTilesLogging(true); // If needed
271
+ const wxapi = new WxAPI({ dataServerURL, maskURL: 'none', qtreeURL: 'none', requestInit });
272
+
273
+ const datasetName = 'gfs.global';
274
+ const variable = 'air.temperature.at-2m'; // Scalar example
275
+ // const variable = 'wind.speed.eastward.at-10m'; // Vector example
276
+
277
+ // Create a dataset manager (may be used for many layers from this dataset)
278
+ const wxdatasetManager = await wxapi.createDatasetManager(datasetName);
279
+
280
+ // Usefull to automatically get the vector component variables from the dataset manager if given variable is northward or eastward
281
+ // if not a vector component, then just return the variable itself
282
+ const variables = wxdatasetManager.checkCombineVariableIfVector(variable);
283
+
284
+ // create a layer
285
+ const leafletOptions: L.GridLayerOptions = { opacity: 1, attribution: 'WxTiles' };
286
+ const wxsource = new WxTileSource({ wxdatasetManager, variables }, leafletOptions);
287
+
288
+ // add the layer to the map
289
+ map.addLayer(wxsource);
290
+
291
+ // await for the first load
292
+ await new Promise((done) => wxsource.once('load', done)); // highly recommended to await for the first load
293
+ }