@superrouteca/smap-cesium 0.0.0-stage → 1.1.1
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/CHANGELOG.md +17 -0
- package/LICENSE +21 -0
- package/README.md +112 -2
- package/package.json +67 -4
- package/src/data.js +243 -0
- package/src/entities.js +195 -0
- package/src/imagery.js +175 -0
- package/src/index.js +6 -0
- package/src/session.js +198 -0
- package/types/data.d.ts +20 -0
- package/types/index.d.ts +102 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 1.1.1 — 2026-10-27
|
|
4
|
+
|
|
5
|
+
- The version follows the shared 1.1.1 release; no change of its own.
|
|
6
|
+
|
|
7
|
+
## 1.1.0 — 2026-10-27
|
|
8
|
+
|
|
9
|
+
- First version.
|
|
10
|
+
- sMap as Cesium imagery (`createBaseLayer`, `setBasemap`, `createImageryProvider`, `createWmtsImageryProvider`):
|
|
11
|
+
the five colour schemes and custom styles, labels in any language, 512 px images, XYZ or WMTS. The map key or token
|
|
12
|
+
on every tile, the nearest map node and a retry on the next one when a node fails, the sMap badge and the
|
|
13
|
+
OpenStreetMap credit on screen.
|
|
14
|
+
- sMap's schemes in Cesium's base layer picker (`providerViewModels`).
|
|
15
|
+
- sMap's points, pins, lines and areas in a viewer with the SDK's options and InfoBox popups (`addSMapData`).
|
|
16
|
+
- Cesium data on an sMap map: CZML, KML / KMZ, GeoJSON and a viewer's entities (`addCesiumData`, `czmlToGeoJSON`,
|
|
17
|
+
`entitiesToGeoJSON`), with what has no 2D counterpart listed.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Goodneo Solutions
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,113 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @superrouteca/smap-cesium
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
sMap and [CesiumJS](https://cesium.com/platform/cesiumjs/) both ways:
|
|
4
|
+
|
|
5
|
+
- **sMap as Cesium imagery**: sMap's raster tiles on the globe in any of the five colour schemes or your saved custom
|
|
6
|
+
styles, labels in any language, through `UrlTemplateImageryProvider` (XYZ) or `WebMapTileServiceImageryProvider`
|
|
7
|
+
(OGC WMTS, tile matrix set `GoogleMapsCompatible`). The map key or token goes with every tile, tiles come from the
|
|
8
|
+
nearest map node and are retried on the next one when a node fails, and the sMap badge and the OpenStreetMap credit
|
|
9
|
+
are shown on screen. No Cesium ion account is needed for the basemap.
|
|
10
|
+
- **sMap's points, pins, lines and areas in a viewer**, with the options of the SDK's `addPoints` / `addLines` /
|
|
11
|
+
`addPolygons` and popups in Cesium's InfoBox.
|
|
12
|
+
- **Cesium-side data on an sMap map**: CZML, KML / KMZ and GeoJSON (and a viewer's entities) shown on an sMap map
|
|
13
|
+
where they have a 2D counterpart.
|
|
14
|
+
|
|
15
|
+
```sh
|
|
16
|
+
npm install @superrouteca/smap-cesium cesium
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
`cesium` 1.x is a peer dependency (not needed for `@superrouteca/smap-cesium/data`). The adapter depends on
|
|
20
|
+
`@superrouteca/smap` (1.1.0) for the nodes, the key, the token and the tile URLs.
|
|
21
|
+
|
|
22
|
+
## Access
|
|
23
|
+
|
|
24
|
+
Every call takes the options of the sMap JS client: `apiKey` (a map key, `smk_…`, whose allowlist names your site),
|
|
25
|
+
or `token` / `getToken` (short-lived tokens from your server), plus `baseUrl` (default `https://tile.srsr.ca`),
|
|
26
|
+
`nodes` and `nearest`. Share one session with `session: createSession({ … })`.
|
|
27
|
+
|
|
28
|
+
## sMap as the globe's imagery
|
|
29
|
+
|
|
30
|
+
```js
|
|
31
|
+
import { Viewer } from 'cesium';
|
|
32
|
+
import { createBaseLayer } from '@superrouteca/smap-cesium';
|
|
33
|
+
|
|
34
|
+
const viewer = new Viewer('globe', {
|
|
35
|
+
baseLayer: createBaseLayer({ apiKey: 'smk_…', style: 'light', language: 'ja' }),
|
|
36
|
+
baseLayerPicker: false,
|
|
37
|
+
geocoder: false,
|
|
38
|
+
});
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
- `style`: `light`, `white`, `grayscale`, `dark`, `black`, or a custom style `custom:sms_…`; `retina: true` for 512 px
|
|
42
|
+
images; `wmts: true` for the WMTS provider.
|
|
43
|
+
- On an existing viewer: `const basemap = setBasemap(viewer, { apiKey: 'smk_…', style: 'dark' })` replaces the first
|
|
44
|
+
imagery layer and keeps everything else; `basemap.setStyle('grayscale')` and `basemap.setLanguage('fr')` change it.
|
|
45
|
+
- The providers on their own: `await createImageryProvider(options)` and `await createWmtsImageryProvider(options)`
|
|
46
|
+
(the WMTS capabilities document is at `provider.smap.capabilities`).
|
|
47
|
+
- Cesium's base layer picker with sMap's schemes:
|
|
48
|
+
`new Viewer('globe', { imageryProviderViewModels: providerViewModels({ apiKey: 'smk_…' }), terrainProviderViewModels: [] })`.
|
|
49
|
+
|
|
50
|
+
Each tile request carries the token as an `Authorization` header (renewed before it expires) and the map key in the
|
|
51
|
+
URL. A tile that fails with a network error or a 5xx answer is retried on the next node, and new tiles start there; a
|
|
52
|
+
401 renews the token once; other 4xx answers are final.
|
|
53
|
+
|
|
54
|
+
## sMap's layers in a viewer
|
|
55
|
+
|
|
56
|
+
```js
|
|
57
|
+
import { addSMapData } from '@superrouteca/smap-cesium';
|
|
58
|
+
import { popupTemplate } from '@superrouteca/smap';
|
|
59
|
+
|
|
60
|
+
await addSMapData(viewer, 'zones', zones, { fill: '#2563eb', opacity: 0.3, extrude: { height: 'height' } });
|
|
61
|
+
await addSMapData(viewer, 'route', route, { color: { property: 'color' }, width: 5 });
|
|
62
|
+
await addSMapData(viewer, 'stops', stops, {
|
|
63
|
+
marker: { text: { property: 'seq' }, border: { property: 'color' } }, label: 'name',
|
|
64
|
+
popup: popupTemplate('<b>{name}</b><br>{address}'),
|
|
65
|
+
});
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Each call adds a `GeoJsonDataSource` named by the id: points as pins (numbered with `marker.text`), lines and areas on
|
|
69
|
+
the ground (`clampToGround: false` to lift them), `extrude` raises areas, `label` writes a property beside each point,
|
|
70
|
+
and the `popup` is each entity's InfoBox description. Colours are constants or `{ property }`; GeoJSON simplestyle
|
|
71
|
+
properties colour a layer that gives none of its own. Clustering, casings, arrows, dashes, count badges and Auto Zoom
|
|
72
|
+
are the sMap map's own and are not drawn here.
|
|
73
|
+
|
|
74
|
+
## Cesium data on an sMap map
|
|
75
|
+
|
|
76
|
+
```js
|
|
77
|
+
import * as sMap from '@superrouteca/smap';
|
|
78
|
+
import { addCesiumData, entitiesToGeoJSON } from '@superrouteca/smap-cesium';
|
|
79
|
+
|
|
80
|
+
const map = new sMap.Map({ container: 'map', apiKey: 'smk_…' });
|
|
81
|
+
const { skipped } = await addCesiumData(map, 'fleet', czmlPackets, { slot: 'top' });
|
|
82
|
+
await addCesiumData(map, 'survey', kmlText, { format: 'kml' });
|
|
83
|
+
map.addData('picked', entitiesToGeoJSON(viewer.entities)); // a viewer's entities as they are now
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
What maps to an sMap map:
|
|
87
|
+
|
|
88
|
+
| Cesium | On the sMap map |
|
|
89
|
+
|---|---|
|
|
90
|
+
| point, billboard, label (at a position) | a point (`marker-color`, `marker-size`, the billboard image as `icon`, the label text as `label`) |
|
|
91
|
+
| polyline | a line (`stroke`, `stroke-opacity`, `stroke-width`) |
|
|
92
|
+
| polygon (with holes), rectangle, ellipse | an area (`fill`, `fill-opacity`, `stroke`); `extrudedHeight` becomes a `height` property, drawn with `extrude: { height: 'height' }` |
|
|
93
|
+
| path of a moving entity | a line through its samples |
|
|
94
|
+
| name, description, properties | `title`, `description` and the feature's own properties (popups read them) |
|
|
95
|
+
| KML / KMZ, GeoJSON, GPX | read by the SDK (`map.addData`), styles as simplestyle |
|
|
96
|
+
|
|
97
|
+
What cannot map, and is listed in `skipped` (never guessed): 3D models (glTF), 3D Tiles tilesets (refused as a whole:
|
|
98
|
+
`addCesiumData` throws), ellipsoids, boxes, cylinders, walls, corridors and polyline volumes, positions given by
|
|
99
|
+
reference, and time: a time-dynamic position is shown at its first sample, and a viewer's entities at the time given
|
|
100
|
+
(`entitiesToGeoJSON(entities, { time })`, default now). Heights above the ground are dropped. Terrain and Cesium ion
|
|
101
|
+
assets have no sMap counterpart.
|
|
102
|
+
|
|
103
|
+
`czmlToGeoJSON(czml)` gives the converted FeatureCollection with its `skipped` list without a map;
|
|
104
|
+
`@superrouteca/smap-cesium/data` holds the CZML functions without the cesium package.
|
|
105
|
+
|
|
106
|
+
## Example
|
|
107
|
+
|
|
108
|
+
[`examples/index.html`](examples/index.html): serve the repository root (`npx serve .`) and open
|
|
109
|
+
`/cesium/examples/?key=smk_…` (`&style=dark`, `&lang=fr`, `&wmts=1`).
|
|
110
|
+
|
|
111
|
+
## Licence
|
|
112
|
+
|
|
113
|
+
MIT. The map data is © OpenStreetMap contributors; the credit stays visible on every map.
|
package/package.json
CHANGED
|
@@ -1,6 +1,69 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@superrouteca/smap-cesium",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.1.1",
|
|
4
|
+
"description": "sMap for CesiumJS: sMap imagery (any scheme, custom style and language) with keys, tokens and node failover, sMap layers as Cesium entities, and Cesium data (CZML, KML, GeoJSON) on sMap maps.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "Goodneo Solutions",
|
|
7
|
+
"homepage": "https://github.com/Goodneo-Solutions/smap-sdk/tree/main/cesium#readme",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/Goodneo-Solutions/smap-sdk.git",
|
|
11
|
+
"directory": "cesium"
|
|
12
|
+
},
|
|
13
|
+
"keywords": [
|
|
14
|
+
"map",
|
|
15
|
+
"maps",
|
|
16
|
+
"cesium",
|
|
17
|
+
"3d",
|
|
18
|
+
"globe",
|
|
19
|
+
"imagery",
|
|
20
|
+
"czml",
|
|
21
|
+
"smap",
|
|
22
|
+
"superroute"
|
|
23
|
+
],
|
|
24
|
+
"type": "module",
|
|
25
|
+
"sideEffects": false,
|
|
26
|
+
"main": "./src/index.js",
|
|
27
|
+
"module": "./src/index.js",
|
|
28
|
+
"types": "./types/index.d.ts",
|
|
29
|
+
"exports": {
|
|
30
|
+
".": {
|
|
31
|
+
"types": "./types/index.d.ts",
|
|
32
|
+
"default": "./src/index.js"
|
|
33
|
+
},
|
|
34
|
+
"./data": {
|
|
35
|
+
"types": "./types/data.d.ts",
|
|
36
|
+
"default": "./src/data.js"
|
|
37
|
+
},
|
|
38
|
+
"./package.json": "./package.json"
|
|
39
|
+
},
|
|
40
|
+
"files": [
|
|
41
|
+
"src",
|
|
42
|
+
"types",
|
|
43
|
+
"README.md",
|
|
44
|
+
"CHANGELOG.md",
|
|
45
|
+
"LICENSE"
|
|
46
|
+
],
|
|
47
|
+
"engines": {
|
|
48
|
+
"node": ">=18"
|
|
49
|
+
},
|
|
50
|
+
"scripts": {
|
|
51
|
+
"test": "node --import ./test/setup.mjs --test test/*.test.mjs",
|
|
52
|
+
"typecheck": "tsc -p test/tsconfig.json"
|
|
53
|
+
},
|
|
54
|
+
"dependencies": {
|
|
55
|
+
"@superrouteca/smap": "1.1.1"
|
|
56
|
+
},
|
|
57
|
+
"peerDependencies": {
|
|
58
|
+
"cesium": "^1.120.0"
|
|
59
|
+
},
|
|
60
|
+
"peerDependenciesMeta": {
|
|
61
|
+
"cesium": {
|
|
62
|
+
"optional": true
|
|
63
|
+
}
|
|
64
|
+
},
|
|
65
|
+
"devDependencies": {
|
|
66
|
+
"cesium": "1.146.0",
|
|
67
|
+
"typescript": "6.0.3"
|
|
68
|
+
}
|
|
69
|
+
}
|
package/src/data.js
ADDED
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
// Cesium-side data on an sMap map (works without the cesium package): CZML converted to GeoJSON with simplestyle
|
|
2
|
+
// colours, and KML / KMZ / GeoJSON / GPX handed to the map's addData as they are. What has no counterpart on a 2D map
|
|
3
|
+
// (3D models, 3D Tiles tilesets, ellipsoids, boxes, cylinders, walls, corridors, time-dynamic values, references) is
|
|
4
|
+
// reported in `skipped`, never guessed.
|
|
5
|
+
|
|
6
|
+
const UNMAPPED = {
|
|
7
|
+
model: '3D model (glTF)',
|
|
8
|
+
tileset: '3D Tiles tileset',
|
|
9
|
+
ellipsoid: 'ellipsoid (a 3D volume)',
|
|
10
|
+
box: 'box (a 3D volume)',
|
|
11
|
+
cylinder: 'cylinder (a 3D volume)',
|
|
12
|
+
wall: 'wall (a vertical surface)',
|
|
13
|
+
corridor: 'corridor (a width in metres along a line)',
|
|
14
|
+
polylineVolume: 'polyline volume (a 3D volume)',
|
|
15
|
+
plane: 'plane',
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
function hexOf(c) {
|
|
19
|
+
if (!c) { return null; }
|
|
20
|
+
let rgba = c.rgba || (c.rgbaf && c.rgbaf.map((v) => v * 255));
|
|
21
|
+
if (!rgba && Array.isArray(c)) { rgba = c; }
|
|
22
|
+
if (!Array.isArray(rgba) || rgba.length < 3) { return null; }
|
|
23
|
+
if (rgba.length > 4) { rgba = rgba.slice(-4); } // a time-tagged colour: its last value
|
|
24
|
+
const h = (n) => Math.max(0, Math.min(255, Math.round(n))).toString(16).padStart(2, '0');
|
|
25
|
+
return { color: '#' + h(rgba[0]) + h(rgba[1]) + h(rgba[2]), opacity: rgba.length > 3 ? Math.round((rgba[3] / 255) * 100) / 100 : 1 };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function colorOfMaterial(m) {
|
|
29
|
+
if (!m) { return null; }
|
|
30
|
+
if (m.solidColor) { return hexOf(m.solidColor.color); }
|
|
31
|
+
for (const k of ['polylineOutline', 'polylineGlow', 'polylineArrow', 'polylineDash', 'grid', 'stripe', 'checkerboard']) {
|
|
32
|
+
if (m[k] && m[k].color) { return hexOf(m[k].color); }
|
|
33
|
+
}
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const WGS84_A = 6378137.0;
|
|
38
|
+
const WGS84_E2 = 6.69437999014e-3;
|
|
39
|
+
|
|
40
|
+
/** Earth-centred (ECEF) metres → [longitude, latitude] in degrees (WGS 84). */
|
|
41
|
+
export function cartesianToDegrees(x, y, z) {
|
|
42
|
+
const lon = Math.atan2(y, x);
|
|
43
|
+
const p = Math.sqrt(x * x + y * y);
|
|
44
|
+
let lat = Math.atan2(z, p * (1 - WGS84_E2));
|
|
45
|
+
for (let i = 0; i < 5; i++) {
|
|
46
|
+
const n = WGS84_A / Math.sqrt(1 - WGS84_E2 * Math.sin(lat) ** 2);
|
|
47
|
+
const h = p / Math.cos(lat) - n;
|
|
48
|
+
lat = Math.atan2(z, p * (1 - WGS84_E2 * (n / (n + h))));
|
|
49
|
+
}
|
|
50
|
+
return [lon * 180 / Math.PI, lat * 180 / Math.PI];
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Positions of a CZML position / positions object as [lng, lat] pairs, plus whether they were time-tagged.
|
|
55
|
+
* Returns null when the positions are a reference or in a form not read here.
|
|
56
|
+
*/
|
|
57
|
+
export function czmlPositions(value, { single = false } = {}) {
|
|
58
|
+
if (!value || typeof value !== 'object') { return null; }
|
|
59
|
+
if (value.reference || value.references) { return null; }
|
|
60
|
+
const forms = [
|
|
61
|
+
['cartographicDegrees', 3, (a) => [a[0], a[1]]],
|
|
62
|
+
['cartographicRadians', 3, (a) => [a[0] * 180 / Math.PI, a[1] * 180 / Math.PI]],
|
|
63
|
+
['cartesian', 3, (a) => cartesianToDegrees(a[0], a[1], a[2])],
|
|
64
|
+
];
|
|
65
|
+
for (const [key, size, convert] of forms) {
|
|
66
|
+
const arr = value[key];
|
|
67
|
+
if (!Array.isArray(arr)) { continue; }
|
|
68
|
+
// A single position given with a time: [t, x, y, z, t, x, y, z, …] (time-tagged samples).
|
|
69
|
+
const tagged = single ? arr.length > size && arr.length % (size + 1) === 0 : Boolean(value.epoch) && arr.length % (size + 1) === 0;
|
|
70
|
+
const step = tagged ? size + 1 : size;
|
|
71
|
+
const off = tagged ? 1 : 0;
|
|
72
|
+
const out = [];
|
|
73
|
+
for (let i = 0; i + step <= arr.length; i += step) { out.push(convert(arr.slice(i + off, i + off + size))); }
|
|
74
|
+
return { positions: out, timed: tagged };
|
|
75
|
+
}
|
|
76
|
+
return null;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function textOf(v) {
|
|
80
|
+
if (v === undefined || v === null) { return undefined; }
|
|
81
|
+
if (typeof v === 'string') { return v; }
|
|
82
|
+
if (typeof v === 'object' && typeof v.string === 'string') { return v.string; }
|
|
83
|
+
return undefined;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function ellipseRing(center, a, b, rotation = 0, steps = 64) {
|
|
87
|
+
const [lng, lat] = center;
|
|
88
|
+
const mPerDegLat = 111320;
|
|
89
|
+
const mPerDegLng = 111320 * Math.cos(lat * Math.PI / 180) || 1e-9;
|
|
90
|
+
const ring = [];
|
|
91
|
+
for (let i = 0; i < steps; i++) {
|
|
92
|
+
const t = (i / steps) * 2 * Math.PI;
|
|
93
|
+
const x = a * Math.cos(t);
|
|
94
|
+
const y = b * Math.sin(t);
|
|
95
|
+
const xr = x * Math.cos(rotation) - y * Math.sin(rotation);
|
|
96
|
+
const yr = x * Math.sin(rotation) + y * Math.cos(rotation);
|
|
97
|
+
ring.push([lng + xr / mPerDegLng, lat + yr / mPerDegLat]);
|
|
98
|
+
}
|
|
99
|
+
return ring;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function num(v) { return typeof v === 'number' ? v : v && typeof v.number === 'number' ? v.number : undefined; }
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* CZML (an array of packets, or its JSON text) as a GeoJSON FeatureCollection: points, billboards and labels become
|
|
106
|
+
* points; polylines lines; polygons, rectangles and ellipses areas; colours, widths and text become simplestyle
|
|
107
|
+
* properties (`marker-color`, `stroke`, `stroke-width`, `fill`, `fill-opacity`, `title`, `description`); a polygon's
|
|
108
|
+
* `extrudedHeight` becomes a `height` property (draw it with `extrude: { height: 'height' }`). Heights are dropped.
|
|
109
|
+
*
|
|
110
|
+
* @returns {{ type: 'FeatureCollection', features: object[], skipped: Array<{ id: string, reason: string }> }}
|
|
111
|
+
*/
|
|
112
|
+
export function czmlToGeoJSON(czml) {
|
|
113
|
+
const packets = typeof czml === 'string' ? JSON.parse(czml) : czml;
|
|
114
|
+
if (!Array.isArray(packets)) { throw new Error('sMap: CZML is an array of packets'); }
|
|
115
|
+
const features = [];
|
|
116
|
+
const skipped = [];
|
|
117
|
+
const skip = (id, reason) => skipped.push({ id: String(id), reason });
|
|
118
|
+
for (const p of packets) {
|
|
119
|
+
if (!p || p.id === 'document') { continue; }
|
|
120
|
+
const id = p.id ?? String(features.length);
|
|
121
|
+
if (p.delete) { skip(id, 'delete packet'); continue; }
|
|
122
|
+
const props = { id };
|
|
123
|
+
if (p.name) { props.title = p.name; props.name = p.name; }
|
|
124
|
+
const description = textOf(p.description);
|
|
125
|
+
if (description) { props.description = description; }
|
|
126
|
+
if (p.properties) { for (const [k, v] of Object.entries(p.properties)) { if (v === null || typeof v !== 'object') { props[k] = v; } else if ('number' in v || 'string' in v || 'boolean' in v) { props[k] = v.number ?? v.string ?? v.boolean; } } }
|
|
127
|
+
for (const k of Object.keys(UNMAPPED)) { if (p[k]) { skip(id, UNMAPPED[k]); } }
|
|
128
|
+
if (p.availability) { props.availability = p.availability; }
|
|
129
|
+
let pos = null;
|
|
130
|
+
if (p.position) {
|
|
131
|
+
pos = czmlPositions(p.position, { single: true });
|
|
132
|
+
if (!pos) { skip(id, 'position given by reference or in a form not read'); }
|
|
133
|
+
else if (pos.timed) { skip(id, 'time-dynamic position (first sample used)'); }
|
|
134
|
+
}
|
|
135
|
+
const at = pos && pos.positions.length ? pos.positions[0] : null;
|
|
136
|
+
let drew = false;
|
|
137
|
+
if (at && (p.point || p.billboard || p.label || (!p.polyline && !p.polygon && !p.ellipse && !p.rectangle && !Object.keys(UNMAPPED).some((k) => p[k])))) {
|
|
138
|
+
const style = { ...props };
|
|
139
|
+
const c = p.point ? hexOf(p.point.color) : p.billboard ? hexOf(p.billboard.color) : null;
|
|
140
|
+
if (c) { style['marker-color'] = c.color; }
|
|
141
|
+
const size = p.point && num(p.point.pixelSize);
|
|
142
|
+
if (size) { style['marker-size'] = size <= 6 ? 'small' : size >= 14 ? 'large' : 'medium'; }
|
|
143
|
+
const label = p.label && textOf(p.label.text);
|
|
144
|
+
if (label) { style.label = label; if (!style.title) { style.title = label; } }
|
|
145
|
+
if (p.billboard && typeof p.billboard.image === 'string') { style.icon = p.billboard.image; }
|
|
146
|
+
features.push({ type: 'Feature', id, properties: style, geometry: { type: 'Point', coordinates: at } });
|
|
147
|
+
drew = true;
|
|
148
|
+
}
|
|
149
|
+
if (p.path && pos && pos.positions.length > 1) {
|
|
150
|
+
const c = colorOfMaterial(p.path.material);
|
|
151
|
+
const style = { ...props, ...(c ? { stroke: c.color, 'stroke-opacity': c.opacity } : {}) };
|
|
152
|
+
if (num(p.path.width)) { style['stroke-width'] = num(p.path.width); }
|
|
153
|
+
features.push({ type: 'Feature', id: id + ':path', properties: style, geometry: { type: 'LineString', coordinates: pos.positions } });
|
|
154
|
+
drew = true;
|
|
155
|
+
}
|
|
156
|
+
if (p.polyline) {
|
|
157
|
+
const line = czmlPositions(p.polyline.positions);
|
|
158
|
+
if (!line || line.positions.length < 2) { skip(id, 'polyline positions given by reference or in a form not read'); }
|
|
159
|
+
else {
|
|
160
|
+
const c = colorOfMaterial(p.polyline.material);
|
|
161
|
+
const style = { ...props, ...(c ? { stroke: c.color, 'stroke-opacity': c.opacity } : {}) };
|
|
162
|
+
if (num(p.polyline.width)) { style['stroke-width'] = num(p.polyline.width); }
|
|
163
|
+
features.push({ type: 'Feature', id, properties: style, geometry: { type: 'LineString', coordinates: line.positions } });
|
|
164
|
+
drew = true;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
const area = (ring, holes, g) => {
|
|
168
|
+
const close = (r) => (r.length && (r[0][0] !== r[r.length - 1][0] || r[0][1] !== r[r.length - 1][1]) ? r.concat([r[0]]) : r);
|
|
169
|
+
const c = g.material ? colorOfMaterial(g.material) : null;
|
|
170
|
+
const style = { ...props };
|
|
171
|
+
if (c) { style.fill = c.color; style['fill-opacity'] = c.opacity; }
|
|
172
|
+
const o = g.outlineColor ? hexOf(g.outlineColor) : null;
|
|
173
|
+
if (o && g.outline !== false) { style.stroke = o.color; }
|
|
174
|
+
if (num(g.outlineWidth)) { style['stroke-width'] = num(g.outlineWidth); }
|
|
175
|
+
if (num(g.extrudedHeight) !== undefined) { style.height = num(g.extrudedHeight); if (num(g.height) !== undefined) { style.base = num(g.height); } }
|
|
176
|
+
features.push({ type: 'Feature', id, properties: style, geometry: { type: 'Polygon', coordinates: [close(ring), ...holes.map(close)] } });
|
|
177
|
+
drew = true;
|
|
178
|
+
};
|
|
179
|
+
if (p.polygon) {
|
|
180
|
+
const outer = czmlPositions(p.polygon.positions);
|
|
181
|
+
if (!outer || outer.positions.length < 3) { skip(id, 'polygon positions given by reference or in a form not read'); }
|
|
182
|
+
else {
|
|
183
|
+
const holes = [];
|
|
184
|
+
const h = p.polygon.holes;
|
|
185
|
+
for (const key of ['cartographicDegrees', 'cartographicRadians', 'cartesian']) {
|
|
186
|
+
if (h && Array.isArray(h[key])) { for (const ring of h[key]) { const r = czmlPositions({ [key]: ring }); if (r) { holes.push(r.positions); } } }
|
|
187
|
+
}
|
|
188
|
+
area(outer.positions, holes, p.polygon);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
if (p.rectangle && p.rectangle.coordinates) {
|
|
192
|
+
const c = p.rectangle.coordinates;
|
|
193
|
+
const w = c.wsenDegrees || (c.wsen && c.wsen.map((v) => v * 180 / Math.PI));
|
|
194
|
+
if (!w) { skip(id, 'rectangle coordinates given by reference or in a form not read'); }
|
|
195
|
+
else { area([[w[0], w[1]], [w[2], w[1]], [w[2], w[3]], [w[0], w[3]]], [], p.rectangle); }
|
|
196
|
+
}
|
|
197
|
+
if (p.ellipse) {
|
|
198
|
+
const a = num(p.ellipse.semiMajorAxis);
|
|
199
|
+
const b = num(p.ellipse.semiMinorAxis);
|
|
200
|
+
if (!at || !a || !b) { skip(id, 'ellipse without a position or axes'); }
|
|
201
|
+
else { area(ellipseRing(at, a, b, num(p.ellipse.rotation) || 0), [], p.ellipse); }
|
|
202
|
+
}
|
|
203
|
+
if (!drew && !skipped.some((s) => s.id === String(id))) { skip(id, 'nothing drawable on a 2D map'); }
|
|
204
|
+
}
|
|
205
|
+
return { type: 'FeatureCollection', features, skipped };
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function looksLikeCzml(input) {
|
|
209
|
+
const v = typeof input === 'string' ? input.trim() : input;
|
|
210
|
+
if (Array.isArray(v)) { return v.length > 0 && v[0] && v[0].id === 'document'; }
|
|
211
|
+
return typeof v === 'string' && /^\[\s*\{[\s\S]*?"id"\s*:\s*"document"/.test(v);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
function looksLikeTileset(input) {
|
|
215
|
+
const v = typeof input === 'string' ? (() => { try { return JSON.parse(input); } catch (e) { return null; } })() : input;
|
|
216
|
+
return Boolean(v && typeof v === 'object' && !Array.isArray(v) && v.asset && v.root && (v.geometricError !== undefined || v.root.geometricError !== undefined));
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* Cesium-side data on an sMap map: CZML is converted (czmlToGeoJSON) and added with `map.addData`; KML, KMZ, GeoJSON
|
|
221
|
+
* and GPX go to `map.addData` as they are (the SDK reads them). A 3D Tiles tileset is refused: it has no counterpart
|
|
222
|
+
* on an sMap map. Layer options (colours, popups, `extrude`, a `slot` …) are passed through.
|
|
223
|
+
*
|
|
224
|
+
* @param {object} map an sMap map (1.1.0 or later)
|
|
225
|
+
* @param {string} id
|
|
226
|
+
* @param {*} input CZML packets or text, a KML / GeoJSON / GPX string, a KMZ Blob / ArrayBuffer, a GeoJSON object
|
|
227
|
+
* @param {object} [options] `format` ('czml' | 'kml' | 'kmz' | 'geojson' | 'gpx'; guessed when omitted) and layer options
|
|
228
|
+
* @returns {Promise<{ format: string, skipped: Array<{ id: string, reason: string }> }>}
|
|
229
|
+
*/
|
|
230
|
+
export async function addCesiumData(map, id, input, options = {}) {
|
|
231
|
+
if (!map || typeof map.addData !== 'function') { throw new Error('sMap: this map has no addData (needs @superrouteca/smap 1.1.0 or later)'); }
|
|
232
|
+
const { format: given, ...layerOptions } = options;
|
|
233
|
+
if (looksLikeTileset(input)) { throw new Error('sMap: a 3D Tiles tileset cannot be shown on an sMap map'); }
|
|
234
|
+
const format = given || (looksLikeCzml(input) ? 'czml' : undefined);
|
|
235
|
+
if (format === 'czml') {
|
|
236
|
+
const fc = czmlToGeoJSON(input);
|
|
237
|
+
await map.addData(id, { type: 'FeatureCollection', features: fc.features }, { ...layerOptions, format: 'geojson' });
|
|
238
|
+
return { format, skipped: fc.skipped };
|
|
239
|
+
}
|
|
240
|
+
const opts = format ? { ...layerOptions, format } : layerOptions;
|
|
241
|
+
await map.addData(id, input, opts);
|
|
242
|
+
return { format: format || 'guessed', skipped: [] };
|
|
243
|
+
}
|
package/src/entities.js
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
// sMap layer data in a Cesium viewer (a GeoJsonDataSource styled with the SDK's point / line / area options, pins with
|
|
2
|
+
// numbers, labels and popups in the InfoBox), and a viewer's entities back to GeoJSON for an sMap map.
|
|
3
|
+
import {
|
|
4
|
+
GeoJsonDataSource, Color, PinBuilder, VerticalOrigin, HorizontalOrigin, LabelStyle, Cartesian2, Cartographic,
|
|
5
|
+
JulianDate, Math as CesiumMath,
|
|
6
|
+
} from 'cesium';
|
|
7
|
+
|
|
8
|
+
const GEOMETRY_TYPES = ['Point', 'MultiPoint', 'LineString', 'MultiLineString', 'Polygon', 'MultiPolygon', 'GeometryCollection'];
|
|
9
|
+
|
|
10
|
+
/** sMap layer data (a FeatureCollection, a Feature, a geometry, or an array of points / features) as features. */
|
|
11
|
+
export function toFeatures(data) {
|
|
12
|
+
if (!data) { return []; }
|
|
13
|
+
if (data.type === 'FeatureCollection') { return data.features || []; }
|
|
14
|
+
if (data.type === 'Feature') { return [data]; }
|
|
15
|
+
if (GEOMETRY_TYPES.includes(data.type)) { return [{ type: 'Feature', properties: {}, geometry: data }]; }
|
|
16
|
+
if (Array.isArray(data)) {
|
|
17
|
+
return data.map((p) => {
|
|
18
|
+
if (p && p.type === 'Feature') { return p; }
|
|
19
|
+
let lng = p.lng ?? p.lon ?? p.longitude;
|
|
20
|
+
let lat = p.lat ?? p.latitude;
|
|
21
|
+
if (p.coordinates) { [lng, lat] = p.coordinates; }
|
|
22
|
+
return { type: 'Feature', id: p.id, properties: p, geometry: { type: 'Point', coordinates: [lng, lat] } };
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
return [];
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function read(value, props, fallback) {
|
|
29
|
+
if (value === undefined || value === null) { return fallback; }
|
|
30
|
+
if (typeof value === 'object' && !Array.isArray(value) && value.property) { return props[value.property] ?? value.default ?? fallback; }
|
|
31
|
+
if (Array.isArray(value) && value[0] === 'get') { return props[value[1]] ?? fallback; }
|
|
32
|
+
return value;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* The simplestyle properties of a feature for sMap layer options (what Cesium's GeoJsonDataSource reads): a property
|
|
37
|
+
* the feature has itself is kept unless the option names a colour.
|
|
38
|
+
*/
|
|
39
|
+
export function simplestyleFor(kind, props, options = {}) {
|
|
40
|
+
const out = {};
|
|
41
|
+
const set = (k, v) => { if (v !== undefined && v !== null) { out[k] = v; } };
|
|
42
|
+
if (kind === 'points') {
|
|
43
|
+
set('marker-color', read(options.marker ? options.marker.border ?? options.color : options.color, props, undefined));
|
|
44
|
+
if (options.radius) { set('marker-size', options.radius <= 4 ? 'small' : options.radius >= 9 ? 'large' : 'medium'); }
|
|
45
|
+
} else if (kind === 'lines') {
|
|
46
|
+
set('stroke', read(options.color, props, undefined));
|
|
47
|
+
set('stroke-width', options.width);
|
|
48
|
+
set('stroke-opacity', options.opacity);
|
|
49
|
+
} else {
|
|
50
|
+
set('fill', read(options.fill ?? options.color, props, undefined));
|
|
51
|
+
set('fill-opacity', options.opacity);
|
|
52
|
+
set('stroke', read(options.outline, props, undefined));
|
|
53
|
+
set('stroke-width', options.outlineWidth);
|
|
54
|
+
}
|
|
55
|
+
return out;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const KIND_OF = { Point: 'points', MultiPoint: 'points', LineString: 'lines', MultiLineString: 'lines', Polygon: 'areas', MultiPolygon: 'areas' };
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* sMap layer data in a Cesium viewer as a GeoJsonDataSource named `id`, with the options of the SDK's addPoints /
|
|
62
|
+
* addLines / addPolygons (colours as constants or `{ property }`, widths, opacity, pins with `marker.text`, a `label`
|
|
63
|
+
* property, `extrude: { height }` for areas) and the layer's `popup` as each entity's InfoBox description. Lines and
|
|
64
|
+
* areas lie on the ground unless `clampToGround: false`.
|
|
65
|
+
*
|
|
66
|
+
* @returns {Promise<GeoJsonDataSource>} already added to `viewer.dataSources`
|
|
67
|
+
*/
|
|
68
|
+
export async function addSMapData(viewer, id, data, options = {}) {
|
|
69
|
+
const features = toFeatures(data).map((f) => {
|
|
70
|
+
const props = { ...(f.properties || {}) };
|
|
71
|
+
const kind = KIND_OF[f.geometry && f.geometry.type] || 'points';
|
|
72
|
+
return { type: 'Feature', id: f.id, geometry: f.geometry, properties: { ...props, ...simplestyleFor(kind, props, options) } };
|
|
73
|
+
});
|
|
74
|
+
const source = await GeoJsonDataSource.load({ type: 'FeatureCollection', features }, {
|
|
75
|
+
clampToGround: options.clampToGround !== false,
|
|
76
|
+
markerSize: options.marker && options.marker.size ? options.marker.size : 36,
|
|
77
|
+
...(options.sourceOptions || {}),
|
|
78
|
+
});
|
|
79
|
+
source.name = id;
|
|
80
|
+
const pins = new PinBuilder();
|
|
81
|
+
const mk = options.marker;
|
|
82
|
+
for (const entity of source.entities.values) {
|
|
83
|
+
const props = entity.properties ? entity.properties.getValue(JulianDate.now()) : {};
|
|
84
|
+
if (entity.billboard && mk && mk.text !== undefined) {
|
|
85
|
+
const text = read(mk.text, props, '');
|
|
86
|
+
if (text !== '' && text !== null) {
|
|
87
|
+
const color = Color.fromCssColorString(String(read(mk.border ?? options.color, props, '#2563eb')));
|
|
88
|
+
entity.billboard.image = pins.fromText(String(text), color, mk.size || 36).toDataURL();
|
|
89
|
+
entity.billboard.verticalOrigin = VerticalOrigin.BOTTOM;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
if (options.label && props[options.label] != null && entity.position) {
|
|
93
|
+
const right = options.labelPosition === 'right';
|
|
94
|
+
entity.label = {
|
|
95
|
+
text: String(props[options.label]), font: '13px sans-serif', fillColor: Color.fromCssColorString('#333333'),
|
|
96
|
+
outlineColor: Color.WHITE, outlineWidth: 3, style: LabelStyle.FILL_AND_OUTLINE,
|
|
97
|
+
horizontalOrigin: right ? HorizontalOrigin.LEFT : HorizontalOrigin.CENTER,
|
|
98
|
+
verticalOrigin: right ? VerticalOrigin.CENTER : VerticalOrigin.TOP,
|
|
99
|
+
pixelOffset: new Cartesian2(right ? 14 : 0, right ? -18 : 4),
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
if (entity.polygon && options.extrude) {
|
|
103
|
+
const h = options.extrude.height;
|
|
104
|
+
const height = typeof h === 'string' ? Number(props[h]) : Number(h);
|
|
105
|
+
if (height > 0) { entity.polygon.extrudedHeight = height; }
|
|
106
|
+
const b = options.extrude.base;
|
|
107
|
+
const base = typeof b === 'string' ? Number(props[b]) : Number(b);
|
|
108
|
+
if (base > 0) { entity.polygon.height = base; }
|
|
109
|
+
}
|
|
110
|
+
if (options.popup) {
|
|
111
|
+
const content = options.popup(props, { type: 'Feature', properties: props });
|
|
112
|
+
if (content && typeof content.then === 'function') {
|
|
113
|
+
entity.description = '…';
|
|
114
|
+
content.then((html) => { entity.description = typeof html === 'string' ? html : (html && html.outerHTML) || ''; }, () => { entity.description = ''; });
|
|
115
|
+
} else if (content) {
|
|
116
|
+
entity.description = typeof content === 'string' ? content : content.outerHTML || '';
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
await viewer.dataSources.add(source);
|
|
121
|
+
return source;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function degrees(cartesian) {
|
|
125
|
+
const c = Cartographic.fromCartesian(cartesian);
|
|
126
|
+
return c ? [CesiumMath.toDegrees(c.longitude), CesiumMath.toDegrees(c.latitude)] : null;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function valueOf(property, time) {
|
|
130
|
+
if (property === undefined || property === null) { return undefined; }
|
|
131
|
+
return typeof property.getValue === 'function' ? property.getValue(time) : property;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function cssOf(color) { return color && typeof color.toCssHexString === 'function' ? color.toCssHexString().slice(0, 7) : undefined; }
|
|
135
|
+
function alphaOf(color) { return color && typeof color.alpha === 'number' ? Math.round(color.alpha * 100) / 100 : undefined; }
|
|
136
|
+
|
|
137
|
+
const UNMAPPED = { model: '3D model', tileset: '3D Tiles tileset', ellipsoid: 'ellipsoid', box: 'box', cylinder: 'cylinder', wall: 'wall', corridor: 'corridor', polylineVolume: 'polyline volume', plane: 'plane' };
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* A viewer's entities (an EntityCollection, a DataSource, or an array of entities), as they are at `time` (default
|
|
141
|
+
* now), as a GeoJSON FeatureCollection with simplestyle colours, for an sMap map's addData. 3D volumes, models and
|
|
142
|
+
* tilesets are listed in `skipped`.
|
|
143
|
+
*/
|
|
144
|
+
export function entitiesToGeoJSON(entities, { time } = {}) {
|
|
145
|
+
const at = time || JulianDate.now();
|
|
146
|
+
const list = Array.isArray(entities) ? entities : entities && entities.entities ? entities.entities.values : (entities && entities.values) || [];
|
|
147
|
+
const features = [];
|
|
148
|
+
const skipped = [];
|
|
149
|
+
for (const e of list) {
|
|
150
|
+
if (e.show === false) { continue; }
|
|
151
|
+
const props = { id: e.id };
|
|
152
|
+
if (e.name) { props.title = e.name; props.name = e.name; }
|
|
153
|
+
const description = valueOf(e.description, at);
|
|
154
|
+
if (typeof description === 'string' && description) { props.description = description; }
|
|
155
|
+
const own = e.properties ? valueOf(e.properties, at) : null;
|
|
156
|
+
if (own) { for (const [k, v] of Object.entries(own)) { if (v === null || typeof v !== 'object') { props[k] = v; } } }
|
|
157
|
+
for (const k of Object.keys(UNMAPPED)) { if (e[k]) { skipped.push({ id: String(e.id), reason: UNMAPPED[k] }); } }
|
|
158
|
+
let drew = false;
|
|
159
|
+
if (e.polyline) {
|
|
160
|
+
const pos = valueOf(e.polyline.positions, at);
|
|
161
|
+
if (Array.isArray(pos) && pos.length > 1) {
|
|
162
|
+
const color = e.polyline.material && valueOf(e.polyline.material.color, at);
|
|
163
|
+
features.push({ type: 'Feature', id: e.id, properties: { ...props, stroke: cssOf(color), 'stroke-opacity': alphaOf(color), 'stroke-width': valueOf(e.polyline.width, at) }, geometry: { type: 'LineString', coordinates: pos.map(degrees).filter(Boolean) } });
|
|
164
|
+
drew = true;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
if (e.polygon) {
|
|
168
|
+
const h = valueOf(e.polygon.hierarchy, at);
|
|
169
|
+
const outer = h && (h.positions || (Array.isArray(h) ? h : null));
|
|
170
|
+
if (outer && outer.length > 2) {
|
|
171
|
+
const ring = (ps) => { const r = ps.map(degrees).filter(Boolean); return r.length ? r.concat([r[0]]) : r; };
|
|
172
|
+
const holes = (h.holes || []).map((x) => ring(x.positions || x));
|
|
173
|
+
const color = e.polygon.material && valueOf(e.polygon.material.color, at);
|
|
174
|
+
const extruded = valueOf(e.polygon.extrudedHeight, at);
|
|
175
|
+
const style = { ...props, fill: cssOf(color), 'fill-opacity': alphaOf(color), stroke: cssOf(valueOf(e.polygon.outlineColor, at)) };
|
|
176
|
+
if (typeof extruded === 'number') { style.height = extruded; }
|
|
177
|
+
features.push({ type: 'Feature', id: e.id, properties: style, geometry: { type: 'Polygon', coordinates: [ring(outer), ...holes] } });
|
|
178
|
+
drew = true;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
if (!drew && e.position && (e.point || e.billboard || e.label || !Object.keys(UNMAPPED).some((k) => e[k]))) {
|
|
182
|
+
const p = valueOf(e.position, at);
|
|
183
|
+
const xy = p ? degrees(p) : null;
|
|
184
|
+
if (xy) {
|
|
185
|
+
const color = e.point ? valueOf(e.point.color, at) : e.billboard ? valueOf(e.billboard.color, at) : undefined;
|
|
186
|
+
const label = e.label ? valueOf(e.label.text, at) : undefined;
|
|
187
|
+
features.push({ type: 'Feature', id: e.id, properties: { ...props, 'marker-color': cssOf(color), ...(label ? { label } : {}) }, geometry: { type: 'Point', coordinates: xy } });
|
|
188
|
+
drew = true;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
if (!drew && !skipped.some((s) => s.id === String(e.id))) { skipped.push({ id: String(e.id), reason: 'nothing drawable on a 2D map at this time' }); }
|
|
192
|
+
}
|
|
193
|
+
for (const f of features) { for (const k of Object.keys(f.properties)) { if (f.properties[k] === undefined) { delete f.properties[k]; } } }
|
|
194
|
+
return { type: 'FeatureCollection', features, skipped };
|
|
195
|
+
}
|
package/src/imagery.js
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
// sMap in CesiumJS: imagery from sMap's raster tiles (contract §5) in any scheme or custom style and label language,
|
|
2
|
+
// with the map key or token on every tile, read from the nearest node and retried on the next one when a node fails.
|
|
3
|
+
import {
|
|
4
|
+
UrlTemplateImageryProvider, WebMapTileServiceImageryProvider, WebMercatorTilingScheme, Resource, Credit,
|
|
5
|
+
ImageryLayer, ProviderViewModel,
|
|
6
|
+
} from 'cesium';
|
|
7
|
+
import { createSession, ATTRIBUTION, FLAVORS, checkStyle } from './session.js';
|
|
8
|
+
|
|
9
|
+
const BADGE = '<span class="smap-badge" style="display:inline-flex;gap:3px;align-items:center;font-weight:600">' +
|
|
10
|
+
'<svg viewBox="0 0 56 56" width="14" height="14" aria-hidden="true" focusable="false">' +
|
|
11
|
+
'<rect x="2" y="2" width="52" height="52" rx="13" fill="#2563eb"/>' +
|
|
12
|
+
'<path d="M38 15H22a8 8 0 0 0 0 16h12a8 8 0 0 1 0 16H18" fill="none" stroke="#fff" stroke-width="7" ' +
|
|
13
|
+
'stroke-linecap="round" stroke-linejoin="round"/></svg>sMap</span>';
|
|
14
|
+
|
|
15
|
+
/** The credit shown on screen: the sMap badge and the OpenStreetMap credit. */
|
|
16
|
+
export function smapCredit() {
|
|
17
|
+
return new Credit(BADGE + ' ' + ATTRIBUTION, true);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* A Resource for sMap tiles: the session's token and key as headers (kept current), and a retry callback that moves a
|
|
22
|
+
* failed tile to the next node (network errors and 5xx; a 4xx is final, except a 401 which renews the token once).
|
|
23
|
+
*/
|
|
24
|
+
export function smapResource(session, url) {
|
|
25
|
+
const resource = new Resource({
|
|
26
|
+
url,
|
|
27
|
+
headers: session.headers(),
|
|
28
|
+
retryAttempts: Math.max(1, session.nodes().length),
|
|
29
|
+
retryCallback: (res, error) => retry(session, res, error),
|
|
30
|
+
});
|
|
31
|
+
follow(session, resource);
|
|
32
|
+
return resource;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// Keeps a Resource on the current node with the current token. A provider holds its own copy of the Resource it was
|
|
36
|
+
// given (`_resource`, the same field since Cesium 1.0), which follows too, so new tiles start on the new node; tiles
|
|
37
|
+
// already asked for are moved by the retry callback.
|
|
38
|
+
function follow(session, resource) {
|
|
39
|
+
session.on('token', () => { resource.headers = { ...(resource.headers || {}), ...session.headers() }; });
|
|
40
|
+
session.on('nodechange', () => { resource.url = session.rebase(resource.url); });
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function followProvider(session, provider, given) {
|
|
44
|
+
const own = provider && provider._resource;
|
|
45
|
+
if (own && own !== given && typeof own === 'object' && 'url' in own) { follow(session, own); }
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function retry(session, res, error) {
|
|
49
|
+
const status = error && (error.statusCode || error.status);
|
|
50
|
+
if (status === 401 && session.client.renewsToken) {
|
|
51
|
+
return session.client.token().then(() => session.ready()).then(() => {
|
|
52
|
+
res.headers = { ...(res.headers || {}), ...session.headers() };
|
|
53
|
+
return true;
|
|
54
|
+
}, () => false);
|
|
55
|
+
}
|
|
56
|
+
if (status && status < 500) { return false; }
|
|
57
|
+
if (!res || !session.nodeOf(res.url)) { return false; }
|
|
58
|
+
const before = session.nodeOf(res.url);
|
|
59
|
+
session.failed(res.url);
|
|
60
|
+
if (session.node() === before) { return false; }
|
|
61
|
+
res.url = session.rebase(res.url);
|
|
62
|
+
res.headers = { ...(res.headers || {}), ...session.headers() };
|
|
63
|
+
return true;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* An imagery provider of sMap's raster tiles (UrlTemplateImageryProvider over `/v1/raster/{style}/{z}/{x}/{y}`).
|
|
68
|
+
*
|
|
69
|
+
* @param {object} options session options (apiKey / token / getToken, baseUrl, nodes, nearest) or `{ session }`,
|
|
70
|
+
* plus `style` (a scheme or `custom:<id>`), `language`, `retina` (512 px images),
|
|
71
|
+
* `minimumLevel`, `maximumLevel` and other UrlTemplateImageryProvider options in `providerOptions`.
|
|
72
|
+
* @returns {Promise<UrlTemplateImageryProvider>} with `smap: { session, style, language }`
|
|
73
|
+
*/
|
|
74
|
+
export async function createImageryProvider(options = {}) {
|
|
75
|
+
const session = createSession(options.session || options);
|
|
76
|
+
await session.ready();
|
|
77
|
+
const style = checkStyle(options.style);
|
|
78
|
+
const url = session.rasterTemplate(style, { language: options.language, retina: options.retina });
|
|
79
|
+
const resource = smapResource(session, url);
|
|
80
|
+
const provider = new UrlTemplateImageryProvider({
|
|
81
|
+
url: resource,
|
|
82
|
+
tilingScheme: new WebMercatorTilingScheme(),
|
|
83
|
+
tileWidth: 256,
|
|
84
|
+
tileHeight: 256,
|
|
85
|
+
minimumLevel: options.minimumLevel ?? 0,
|
|
86
|
+
maximumLevel: options.maximumLevel ?? 19,
|
|
87
|
+
credit: smapCredit(),
|
|
88
|
+
...(options.providerOptions || {}),
|
|
89
|
+
});
|
|
90
|
+
followProvider(session, provider, resource);
|
|
91
|
+
provider.smap = { session, style, language: options.language };
|
|
92
|
+
return provider;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* The same imagery through OGC WMTS (RESTful, tile matrix set GoogleMapsCompatible), for apps that configure Cesium
|
|
97
|
+
* by WMTS. Each scheme or custom style is a WMTS layer.
|
|
98
|
+
*/
|
|
99
|
+
export async function createWmtsImageryProvider(options = {}) {
|
|
100
|
+
const session = createSession(options.session || options);
|
|
101
|
+
await session.ready();
|
|
102
|
+
const style = checkStyle(options.style);
|
|
103
|
+
const url = session.rasterTemplate(style, {
|
|
104
|
+
language: options.language, retina: options.retina,
|
|
105
|
+
placeholders: { z: '{TileMatrix}', x: '{TileCol}', y: '{TileRow}' },
|
|
106
|
+
});
|
|
107
|
+
const resource = smapResource(session, url);
|
|
108
|
+
const provider = new WebMapTileServiceImageryProvider({
|
|
109
|
+
url: resource,
|
|
110
|
+
layer: style,
|
|
111
|
+
style: 'default',
|
|
112
|
+
format: 'image/png',
|
|
113
|
+
tileMatrixSetID: 'GoogleMapsCompatible',
|
|
114
|
+
tilingScheme: new WebMercatorTilingScheme(),
|
|
115
|
+
maximumLevel: options.maximumLevel ?? 19,
|
|
116
|
+
credit: smapCredit(),
|
|
117
|
+
...(options.providerOptions || {}),
|
|
118
|
+
});
|
|
119
|
+
followProvider(session, provider, resource);
|
|
120
|
+
provider.smap = { session, style, language: options.language, capabilities: session.wmtsCapabilitiesUrl() };
|
|
121
|
+
return provider;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* An ImageryLayer of sMap imagery, usable at once (for `new Viewer(el, { baseLayer: createBaseLayer({ … }) })`); the
|
|
126
|
+
* provider arrives when the nearest node is known. `wmts: true` uses the WMTS provider.
|
|
127
|
+
*/
|
|
128
|
+
export function createBaseLayer(options = {}) {
|
|
129
|
+
const provider = options.wmts ? createWmtsImageryProvider(options) : createImageryProvider(options);
|
|
130
|
+
return ImageryLayer.fromProviderAsync(provider, options.layerOptions || {});
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Makes sMap the base imagery of a viewer (replacing its first imagery layer) and returns a handle to change the
|
|
135
|
+
* style or the language later; other imagery layers, entities and 3D content stay.
|
|
136
|
+
*/
|
|
137
|
+
export function setBasemap(viewer, options = {}) {
|
|
138
|
+
let current = { ...options };
|
|
139
|
+
const layers = viewer.imageryLayers;
|
|
140
|
+
let layer = createBaseLayer(current);
|
|
141
|
+
if (layers.length > 0) { layers.remove(layers.get(0), true); }
|
|
142
|
+
layers.add(layer, 0);
|
|
143
|
+
const replace = (next) => {
|
|
144
|
+
current = { ...current, ...next };
|
|
145
|
+
const fresh = createBaseLayer(current);
|
|
146
|
+
const i = layers.indexOf(layer);
|
|
147
|
+
layers.add(fresh, i < 0 ? 0 : i);
|
|
148
|
+
if (i >= 0) { layers.remove(layer, true); }
|
|
149
|
+
layer = fresh;
|
|
150
|
+
return handle;
|
|
151
|
+
};
|
|
152
|
+
const handle = {
|
|
153
|
+
get layer() { return layer; },
|
|
154
|
+
setStyle(style) { return replace({ style }); },
|
|
155
|
+
setLanguage(language) { return replace({ language }); },
|
|
156
|
+
remove() { layers.remove(layer, true); },
|
|
157
|
+
};
|
|
158
|
+
return handle;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* ProviderViewModels for Cesium's BaseLayerPicker, one per scheme (and custom style): pass them as the viewer's
|
|
163
|
+
* `imageryProviderViewModels`.
|
|
164
|
+
*/
|
|
165
|
+
export function providerViewModels(options = {}) {
|
|
166
|
+
const session = createSession(options.session || options);
|
|
167
|
+
const styles = options.styles || FLAVORS;
|
|
168
|
+
return styles.map((style) => new ProviderViewModel({
|
|
169
|
+
name: (options.labels && options.labels[style]) || 'sMap ' + style.replace(/^custom:/, ''),
|
|
170
|
+
tooltip: 'sMap ' + style,
|
|
171
|
+
category: options.category || 'sMap',
|
|
172
|
+
iconUrl: options.iconUrl || session.rasterTemplate(style, { language: options.language }).replace('{z}', '3').replace('{x}', '2').replace('{y}', '2'),
|
|
173
|
+
creationFunction: () => createImageryProvider({ ...options, session, style }),
|
|
174
|
+
}));
|
|
175
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
// @superrouteca/smap-cesium — sMap and CesiumJS both ways.
|
|
2
|
+
export { Session, createSession, FLAVORS, ATTRIBUTION } from './session.js';
|
|
3
|
+
export { createImageryProvider, createWmtsImageryProvider, createBaseLayer, setBasemap, providerViewModels, smapResource, smapCredit } from './imagery.js';
|
|
4
|
+
export { addSMapData, entitiesToGeoJSON, simplestyleFor, toFeatures } from './entities.js';
|
|
5
|
+
export { czmlToGeoJSON, czmlPositions, cartesianToDegrees, addCesiumData } from './data.js';
|
|
6
|
+
export const version = '1.1.1';
|
package/src/session.js
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
// One connection to sMap for a tool adapter: the JS client of @superrouteca/smap (nearest node, failover, map key,
|
|
2
|
+
// token and its refresh) plus the URLs a tool needs on the node read from now (built by the SDK's styleUrl, rasterUrl
|
|
3
|
+
// and rasterTileJsonUrl) and the headers a tool's own requests carry. The node, key, token and URL logic is the
|
|
4
|
+
// SDK's; this file only asks it.
|
|
5
|
+
//
|
|
6
|
+
// The same file is used by @superrouteca/smap-deckgl, -arcgis and -cesium.
|
|
7
|
+
import SMapClient from '@superrouteca/smap/client';
|
|
8
|
+
import { styleUrl as sdkStyleUrl, rasterUrl as sdkRasterUrl, rasterTileJsonUrl as sdkRasterTileJsonUrl } from '@superrouteca/smap';
|
|
9
|
+
|
|
10
|
+
export const FLAVORS = ['light', 'white', 'grayscale', 'dark', 'black'];
|
|
11
|
+
export const ATTRIBUTION = '© OpenStreetMap contributors';
|
|
12
|
+
export const DEFAULT_BASE = 'https://tile.srsr.ca';
|
|
13
|
+
|
|
14
|
+
const strip = (u) => String(u).replace(/\/+$/, '');
|
|
15
|
+
|
|
16
|
+
/** `light` → `light`; `custom:sms_…` → `custom:sms_…`; anything else is refused with a message naming it. */
|
|
17
|
+
export function checkStyle(style) {
|
|
18
|
+
const s = style == null ? 'light' : String(style);
|
|
19
|
+
if (FLAVORS.includes(s)) { return s; }
|
|
20
|
+
if (/^custom:[A-Za-z0-9_-]+$/.test(s)) { return s; }
|
|
21
|
+
throw new Error('sMap: unknown style "' + s + '" (one of ' + FLAVORS.join(', ') + ', or custom:<id>)');
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function addQuery(url, params) {
|
|
25
|
+
const parts = [];
|
|
26
|
+
for (const [k, v] of Object.entries(params)) {
|
|
27
|
+
if (v !== undefined && v !== null && v !== '') { parts.push(k + '=' + encodeURIComponent(v)); }
|
|
28
|
+
}
|
|
29
|
+
return parts.length ? url + (url.includes('?') ? '&' : '?') + parts.join('&') : url;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export class Session {
|
|
33
|
+
/**
|
|
34
|
+
* @param {object} options the JS client's options (baseUrl, apiKey, token, getToken, nodes, nearest, fetch,
|
|
35
|
+
* timeoutMs), or `{ client }` with a client of your own. `baseUrl` defaults to tile.srsr.ca.
|
|
36
|
+
*/
|
|
37
|
+
constructor(options = {}) {
|
|
38
|
+
if (options instanceof Session) { return options; }
|
|
39
|
+
this.client = options.client || new SMapClient({ ...options, baseUrl: options.baseUrl || DEFAULT_BASE });
|
|
40
|
+
this.baseUrl = this.client.baseUrl;
|
|
41
|
+
this.apiKey = options.apiKey || (options.client && options.client.apiKey) || null;
|
|
42
|
+
this._seeds = (options.nodes || []).map(strip);
|
|
43
|
+
this._order = [this.baseUrl];
|
|
44
|
+
this._token = options.token || null;
|
|
45
|
+
this._listeners = { nodechange: [], token: [] };
|
|
46
|
+
this._timer = null;
|
|
47
|
+
this._ready = null;
|
|
48
|
+
this._closed = false;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Resolves once the nearest node is known and a token (where one is used) is at hand. */
|
|
52
|
+
ready() {
|
|
53
|
+
if (!this._ready) {
|
|
54
|
+
this._ready = Promise.all([this.client.nodes(), this.client.token()]).then(([nodes, token]) => {
|
|
55
|
+
this._order = nodes && nodes.length ? nodes.slice() : [this.baseUrl];
|
|
56
|
+
this._setToken(token);
|
|
57
|
+
return this;
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
return this._ready;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** The node read from now: the nearest one that has not failed. */
|
|
64
|
+
node() { return this._order[0] || this.baseUrl; }
|
|
65
|
+
|
|
66
|
+
/** Every node in the order they are tried. */
|
|
67
|
+
nodes() { return this._order.slice(); }
|
|
68
|
+
|
|
69
|
+
/** The token sent now (kept fresh in the background), or null. */
|
|
70
|
+
token() { return this._token; }
|
|
71
|
+
|
|
72
|
+
_setToken(token) {
|
|
73
|
+
const changed = token !== this._token;
|
|
74
|
+
this._token = token || null;
|
|
75
|
+
if (changed) { this._emit('token', this._token); }
|
|
76
|
+
this._schedule();
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// The client renews a token two minutes before it expires; the adapters read it synchronously (request hooks and
|
|
80
|
+
// tile URLs cannot wait), so it is asked again shortly before that moment.
|
|
81
|
+
_schedule() {
|
|
82
|
+
clearTimeout(this._timer);
|
|
83
|
+
if (this._closed || !this._token || !this.client.renewsToken) { return; }
|
|
84
|
+
const exp = SMapClient.tokenExpiry(this._token);
|
|
85
|
+
if (!exp) { return; }
|
|
86
|
+
const wait = Math.max(5, exp - Math.floor(Date.now() / 1000) - 110) * 1000;
|
|
87
|
+
this._timer = setTimeout(() => {
|
|
88
|
+
this.client.token().then((t) => this._setToken(t), () => { this._timer = setTimeout(() => this._schedule(), 30000); });
|
|
89
|
+
}, Math.min(wait, 2147483000));
|
|
90
|
+
if (this._timer && this._timer.unref) { this._timer.unref(); }
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** The headers a request to sMap carries: the token and the map key. */
|
|
94
|
+
headers() {
|
|
95
|
+
const h = {};
|
|
96
|
+
if (this._token) { h.Authorization = 'Bearer ' + this._token; }
|
|
97
|
+
if (this.apiKey) { h['X-SMap-Key'] = this.apiKey; }
|
|
98
|
+
return h;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Every address requests to sMap may go to (base, seeds, measured nodes). */
|
|
102
|
+
origins() { return [...new Set([this.baseUrl, ...this._seeds, ...this._order])]; }
|
|
103
|
+
|
|
104
|
+
/** The node a URL is on, or null when it is not an sMap URL. */
|
|
105
|
+
nodeOf(url) {
|
|
106
|
+
const u = String(url);
|
|
107
|
+
return this.origins().filter((o) => u === o || u.startsWith(o + '/')).sort((a, b) => b.length - a.length)[0] || null;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** The path (with query) of an sMap URL, or null. */
|
|
111
|
+
pathOf(url) {
|
|
112
|
+
const n = this.nodeOf(url);
|
|
113
|
+
return n === null ? null : String(url).slice(n.length) || '/';
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** The same sMap URL on the node read from now; other URLs unchanged. */
|
|
117
|
+
rebase(url) {
|
|
118
|
+
const p = this.pathOf(url);
|
|
119
|
+
return p === null ? url : this.node() + p;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* A node did not answer: it moves to the end and the next one is read from. Returns true when the node read from
|
|
124
|
+
* changed (callers then re-point their tile URLs).
|
|
125
|
+
*/
|
|
126
|
+
failed(urlOrNode) {
|
|
127
|
+
const n = this.nodeOf(urlOrNode) || strip(urlOrNode);
|
|
128
|
+
const i = this._order.indexOf(n);
|
|
129
|
+
if (i < 0 || this._order.length < 2) { return false; }
|
|
130
|
+
const before = this.node();
|
|
131
|
+
this._order.splice(i, 1);
|
|
132
|
+
this._order.push(n);
|
|
133
|
+
// The client's own order follows, so its requests (styles, TileJSON) and these tile URLs agree.
|
|
134
|
+
if (typeof this.client.demote === 'function') { this.client.demote(n); }
|
|
135
|
+
if (this.node() !== before) { this._emit('nodechange', this.node()); return true; }
|
|
136
|
+
return false;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** Style URL of a scheme or a saved custom style (`custom:<id>`), with labels in `language`, on the current node. */
|
|
140
|
+
styleUrl(style, language) {
|
|
141
|
+
return sdkStyleUrl(checkStyle(style), { baseUrl: this.node(), lang: language, apiKey: this.apiKey || undefined });
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** TileJSON URL of a vector source (default the basemap). */
|
|
145
|
+
tileJsonUrl(source = 'basemap') {
|
|
146
|
+
return addQuery(this.node() + '/v1/tiles/' + encodeURIComponent(source), { key: this.apiKey });
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Raster tile template (contract §5): `{z}/{x}/{y}` by default; `placeholders` renames them for tools with their
|
|
151
|
+
* own (`{ z: '{level}', x: '{col}', y: '{row}' }`).
|
|
152
|
+
*/
|
|
153
|
+
rasterTemplate(style, { language, retina = false, placeholders } = {}) {
|
|
154
|
+
const url = sdkRasterUrl(checkStyle(style), { baseUrl: this.node(), lang: language, retina, apiKey: this.apiKey || undefined });
|
|
155
|
+
const p = placeholders || {};
|
|
156
|
+
return url.replace('{z}', p.z || '{z}').replace('{x}', p.x || '{x}').replace('{y}', p.y || '{y}');
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** TileJSON (raster) of a style. */
|
|
160
|
+
rasterTileJsonUrl(style, { language } = {}) {
|
|
161
|
+
return sdkRasterTileJsonUrl(checkStyle(style), { baseUrl: this.node(), lang: language, apiKey: this.apiKey || undefined });
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** WMTS 1.0.0 capabilities of the raster styles. */
|
|
165
|
+
wmtsCapabilitiesUrl() {
|
|
166
|
+
return addQuery(this.node() + '/v1/raster/wmts', { SERVICE: 'WMTS', REQUEST: 'GetCapabilities', key: this.apiKey });
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Fetches a URL: sMap URLs through the client (nearest node, the next one on failure, token and key); any other URL
|
|
171
|
+
* with plain fetch.
|
|
172
|
+
*/
|
|
173
|
+
fetch(url, init) {
|
|
174
|
+
const path = this.pathOf(url);
|
|
175
|
+
if (path === null) { return globalThis.fetch(url, init); }
|
|
176
|
+
const extra = {};
|
|
177
|
+
const h = init && init.headers;
|
|
178
|
+
if (h) { for (const [k, v] of (typeof h.entries === 'function' ? h.entries() : Object.entries(h))) { extra[k] = v; } }
|
|
179
|
+
return this.client.request(path, extra);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** The style document of a scheme or custom style, read through the client. */
|
|
183
|
+
style(style, language) {
|
|
184
|
+
return this.fetch(this.styleUrl(style, language)).then((r) => r.json());
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
on(type, fn) { (this._listeners[type] || (this._listeners[type] = [])).push(fn); return () => this.off(type, fn); }
|
|
188
|
+
off(type, fn) { const l = this._listeners[type] || []; const i = l.indexOf(fn); if (i >= 0) { l.splice(i, 1); } }
|
|
189
|
+
_emit(type, value) { for (const fn of (this._listeners[type] || []).slice()) { try { fn(value); } catch (e) { /* listener */ } } }
|
|
190
|
+
|
|
191
|
+
/** Stops the token refresh. */
|
|
192
|
+
close() { this._closed = true; clearTimeout(this._timer); }
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** A session from options, or the session given. */
|
|
196
|
+
export function createSession(options) {
|
|
197
|
+
return options instanceof Session ? options : new Session(options || {});
|
|
198
|
+
}
|
package/types/data.d.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// Types of @superrouteca/smap-cesium/data (Cesium-side data on an sMap map; no cesium package needed).
|
|
2
|
+
import type { Map as SMapMap } from '@superrouteca/smap';
|
|
3
|
+
|
|
4
|
+
export interface Skipped { id: string; reason: string }
|
|
5
|
+
export interface CzmlFeatureCollection {
|
|
6
|
+
type: 'FeatureCollection';
|
|
7
|
+
features: Array<{ type: 'Feature'; id: string; properties: Record<string, unknown>; geometry: { type: string; coordinates: unknown } }>;
|
|
8
|
+
/** What has no counterpart on a 2D map, with the reason. */
|
|
9
|
+
skipped: Skipped[];
|
|
10
|
+
}
|
|
11
|
+
export declare function czmlToGeoJSON(czml: unknown[] | string): CzmlFeatureCollection;
|
|
12
|
+
export declare function czmlPositions(value: Record<string, unknown>, options?: { single?: boolean }): { positions: Array<[number, number]>; timed: boolean } | null;
|
|
13
|
+
export declare function cartesianToDegrees(x: number, y: number, z: number): [number, number];
|
|
14
|
+
export interface AddCesiumDataOptions {
|
|
15
|
+
/** Guessed when omitted (CZML from its document packet; other formats by the SDK). */
|
|
16
|
+
format?: 'czml' | 'kml' | 'kmz' | 'geojson' | 'gpx';
|
|
17
|
+
/** Layer options of addData (colours, popups, extrude, slot, …). */
|
|
18
|
+
[option: string]: unknown;
|
|
19
|
+
}
|
|
20
|
+
export declare function addCesiumData(map: SMapMap, id: string, input: unknown, options?: AddCesiumDataOptions): Promise<{ format: string; skipped: Skipped[] }>;
|
package/types/index.d.ts
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
// Types of @superrouteca/smap-cesium.
|
|
2
|
+
import type {
|
|
3
|
+
UrlTemplateImageryProvider, WebMapTileServiceImageryProvider, ImageryLayer, ProviderViewModel, Resource, Credit,
|
|
4
|
+
GeoJsonDataSource, Viewer, Entity, EntityCollection, DataSource, JulianDate,
|
|
5
|
+
} from 'cesium';
|
|
6
|
+
import type SMapClient from '@superrouteca/smap/client';
|
|
7
|
+
import type { LayerData, PointOptions, LineOptions, PolygonOptions, GeoJSONFeature } from '@superrouteca/smap';
|
|
8
|
+
|
|
9
|
+
export * from './data.js';
|
|
10
|
+
|
|
11
|
+
/** A colour scheme, or a saved custom style as `custom:<id>`. */
|
|
12
|
+
export type StyleName = 'light' | 'white' | 'grayscale' | 'dark' | 'black' | `custom:${string}`;
|
|
13
|
+
|
|
14
|
+
export interface SessionOptions {
|
|
15
|
+
/** The public sMap address (default https://tile.srsr.ca). */
|
|
16
|
+
baseUrl?: string;
|
|
17
|
+
/** A map key (`smk_…`). */
|
|
18
|
+
apiKey?: string;
|
|
19
|
+
token?: string;
|
|
20
|
+
/** Called at start and again before each token expires. */
|
|
21
|
+
getToken?: () => string | Promise<string>;
|
|
22
|
+
nodes?: string[];
|
|
23
|
+
nearest?: boolean;
|
|
24
|
+
fetch?: typeof fetch;
|
|
25
|
+
timeoutMs?: number;
|
|
26
|
+
client?: SMapClient;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** One connection to sMap: nearest node, failover, key and token (through the JS client), and the URLs tools need. */
|
|
30
|
+
export declare class Session {
|
|
31
|
+
constructor(options?: SessionOptions);
|
|
32
|
+
readonly client: SMapClient;
|
|
33
|
+
readonly baseUrl: string;
|
|
34
|
+
readonly apiKey: string | null;
|
|
35
|
+
ready(): Promise<this>;
|
|
36
|
+
node(): string;
|
|
37
|
+
nodes(): string[];
|
|
38
|
+
token(): string | null;
|
|
39
|
+
headers(): Record<string, string>;
|
|
40
|
+
origins(): string[];
|
|
41
|
+
nodeOf(url: string): string | null;
|
|
42
|
+
pathOf(url: string): string | null;
|
|
43
|
+
rebase(url: string): string;
|
|
44
|
+
failed(urlOrNode: string): boolean;
|
|
45
|
+
styleUrl(style?: StyleName, language?: string): string;
|
|
46
|
+
tileJsonUrl(source?: string): string;
|
|
47
|
+
rasterTemplate(style?: StyleName, options?: { language?: string; retina?: boolean; placeholders?: { z?: string; x?: string; y?: string } }): string;
|
|
48
|
+
rasterTileJsonUrl(style?: StyleName, options?: { language?: string }): string;
|
|
49
|
+
wmtsCapabilitiesUrl(): string;
|
|
50
|
+
fetch(url: string, init?: RequestInit): Promise<Response>;
|
|
51
|
+
style(style?: StyleName, language?: string): Promise<Record<string, unknown>>;
|
|
52
|
+
on(type: 'nodechange' | 'token', fn: (value: string | null) => void): () => void;
|
|
53
|
+
off(type: 'nodechange' | 'token', fn: (value: string | null) => void): void;
|
|
54
|
+
close(): void;
|
|
55
|
+
}
|
|
56
|
+
export declare function createSession(options?: SessionOptions | Session): Session;
|
|
57
|
+
export declare const FLAVORS: Array<'light' | 'white' | 'grayscale' | 'dark' | 'black'>;
|
|
58
|
+
export declare const ATTRIBUTION: string;
|
|
59
|
+
export declare const version: string;
|
|
60
|
+
|
|
61
|
+
export interface ImageryOptions extends SessionOptions {
|
|
62
|
+
session?: Session;
|
|
63
|
+
style?: StyleName;
|
|
64
|
+
/** Label language (BCP 47). */
|
|
65
|
+
language?: string;
|
|
66
|
+
/** 512 px images. */
|
|
67
|
+
retina?: boolean;
|
|
68
|
+
minimumLevel?: number;
|
|
69
|
+
/** Default 19. */
|
|
70
|
+
maximumLevel?: number;
|
|
71
|
+
/** Other options of the Cesium provider. */
|
|
72
|
+
providerOptions?: Record<string, unknown>;
|
|
73
|
+
}
|
|
74
|
+
export interface ImageryInfo { session: Session; style: StyleName; language?: string }
|
|
75
|
+
export declare function createImageryProvider(options?: ImageryOptions): Promise<UrlTemplateImageryProvider & { smap: ImageryInfo }>;
|
|
76
|
+
export declare function createWmtsImageryProvider(options?: ImageryOptions): Promise<WebMapTileServiceImageryProvider & { smap: ImageryInfo & { capabilities: string } }>;
|
|
77
|
+
export declare function createBaseLayer(options?: ImageryOptions & { wmts?: boolean; layerOptions?: ImageryLayer.ConstructorOptions }): ImageryLayer;
|
|
78
|
+
export interface BasemapHandle {
|
|
79
|
+
readonly layer: ImageryLayer;
|
|
80
|
+
setStyle(style: StyleName): this;
|
|
81
|
+
setLanguage(language: string): this;
|
|
82
|
+
remove(): void;
|
|
83
|
+
}
|
|
84
|
+
export declare function setBasemap(viewer: Pick<Viewer, 'imageryLayers'>, options?: ImageryOptions & { wmts?: boolean }): BasemapHandle;
|
|
85
|
+
export declare function providerViewModels(options?: ImageryOptions & { styles?: StyleName[]; labels?: Record<string, string>; category?: string; iconUrl?: string }): ProviderViewModel[];
|
|
86
|
+
export declare function smapResource(session: Session, url: string): Resource;
|
|
87
|
+
export declare function smapCredit(): Credit;
|
|
88
|
+
|
|
89
|
+
export interface CesiumDataExtras {
|
|
90
|
+
/** Lines and areas on the ground (default true). */
|
|
91
|
+
clampToGround?: boolean;
|
|
92
|
+
/** Other options of GeoJsonDataSource.load. */
|
|
93
|
+
sourceOptions?: GeoJsonDataSource.LoadOptions;
|
|
94
|
+
}
|
|
95
|
+
export declare function addSMapData(viewer: Pick<Viewer, 'dataSources'>, id: string, data: LayerData, options?: (PointOptions | LineOptions | PolygonOptions) & CesiumDataExtras): Promise<GeoJsonDataSource>;
|
|
96
|
+
export declare function entitiesToGeoJSON(entities: EntityCollection | DataSource | Entity[], options?: { time?: JulianDate }): {
|
|
97
|
+
type: 'FeatureCollection';
|
|
98
|
+
features: GeoJSONFeature[];
|
|
99
|
+
skipped: Array<{ id: string; reason: string }>;
|
|
100
|
+
};
|
|
101
|
+
export declare function simplestyleFor(kind: 'points' | 'lines' | 'areas', properties: Record<string, unknown>, options?: Record<string, unknown>): Record<string, string | number>;
|
|
102
|
+
export declare function toFeatures(data: LayerData): GeoJSONFeature[];
|