@celljs/ta-geo 0.0.0-stage → 4.30.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/geo-mvt.js ADDED
@@ -0,0 +1,216 @@
1
+ "use strict";
2
+ // Vector tiles (GeoMvt): the Mapbox Vector Tile format, version 2, that the maps of the web serve, read without a
3
+ // library: the protobuf of its layers, the keys and values of their features, the commands of their geometry made
4
+ // points, lines and rings in the units of the tile (0 to its extent).
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.GeoMvt = void 0;
7
+ /** Reads the protobuf of a tile: varints, fixed numbers and lengths of bytes. */
8
+ class Pbf {
9
+ constructor(buf, end = buf.length) {
10
+ this.buf = buf;
11
+ this.end = end;
12
+ this.pos = 0;
13
+ }
14
+ varint() {
15
+ let value = 0;
16
+ let shift = 0;
17
+ let byte;
18
+ do {
19
+ byte = this.buf[this.pos++];
20
+ value += (byte & 0x7f) * 2 ** shift;
21
+ shift += 7;
22
+ } while (byte & 0x80 && shift < 70);
23
+ return value;
24
+ }
25
+ svarint() {
26
+ const n = this.varint();
27
+ return n % 2 === 1 ? (n + 1) / -2 : n / 2;
28
+ }
29
+ bytes() {
30
+ const length = this.varint();
31
+ const start = this.pos;
32
+ this.pos += length;
33
+ return this.buf.subarray(start, start + length);
34
+ }
35
+ /** Skips a field of the wire type. */
36
+ skip(wire) {
37
+ if (wire === 0) {
38
+ this.varint();
39
+ }
40
+ else if (wire === 1) {
41
+ this.pos += 8;
42
+ }
43
+ else if (wire === 2) {
44
+ this.pos += this.varint();
45
+ }
46
+ else if (wire === 5) {
47
+ this.pos += 4;
48
+ }
49
+ else {
50
+ throw new Error(`Unknown wire type ${wire}`);
51
+ }
52
+ }
53
+ packed() {
54
+ const inner = new Pbf(this.bytes());
55
+ const out = [];
56
+ while (inner.pos < inner.end) {
57
+ out.push(inner.varint());
58
+ }
59
+ return out;
60
+ }
61
+ }
62
+ const decoder = new TextDecoder();
63
+ function value(bytes) {
64
+ const pbf = new Pbf(bytes);
65
+ let out = '';
66
+ while (pbf.pos < pbf.end) {
67
+ const tag = pbf.varint();
68
+ const field = Math.floor(tag / 8);
69
+ const view = new DataView(bytes.buffer, bytes.byteOffset + pbf.pos);
70
+ switch (field) {
71
+ case 1:
72
+ out = decoder.decode(pbf.bytes());
73
+ break;
74
+ case 2:
75
+ out = view.getFloat32(0, true);
76
+ pbf.pos += 4;
77
+ break;
78
+ case 3:
79
+ out = view.getFloat64(0, true);
80
+ pbf.pos += 8;
81
+ break;
82
+ case 4:
83
+ case 5:
84
+ out = pbf.varint();
85
+ break;
86
+ case 6:
87
+ out = pbf.svarint();
88
+ break;
89
+ case 7:
90
+ out = pbf.varint() !== 0;
91
+ break;
92
+ default:
93
+ pbf.skip(tag & 7);
94
+ }
95
+ }
96
+ return out;
97
+ }
98
+ /** The parts of a geometry from its commands: MoveTo starts a part, LineTo goes on, ClosePath closes a ring. */
99
+ function geometry(commands, type) {
100
+ const parts = [];
101
+ let part = [];
102
+ let x = 0;
103
+ let y = 0;
104
+ let i = 0;
105
+ const zigzag = (n) => (n % 2 === 1 ? (n + 1) / -2 : n / 2);
106
+ while (i < commands.length) {
107
+ const command = commands[i] & 7;
108
+ const count = commands[i] >>> 3;
109
+ i++;
110
+ if (command === 7) {
111
+ if (part.length > 0) {
112
+ part.push([part[0][0], part[0][1]]);
113
+ }
114
+ continue;
115
+ }
116
+ for (let k = 0; k < count && i + 1 < commands.length; k++) {
117
+ x += zigzag(commands[i++]);
118
+ y += zigzag(commands[i++]);
119
+ if (command === 1 && type !== 1) {
120
+ if (part.length > 0) {
121
+ parts.push(part);
122
+ }
123
+ part = [];
124
+ }
125
+ part.push([x, y]);
126
+ }
127
+ }
128
+ if (part.length > 0) {
129
+ parts.push(part);
130
+ }
131
+ return parts;
132
+ }
133
+ function layer(bytes) {
134
+ const pbf = new Pbf(bytes);
135
+ let name = '';
136
+ let extent = 4096;
137
+ const keys = [];
138
+ const values = [];
139
+ const raw = [];
140
+ while (pbf.pos < pbf.end) {
141
+ const tag = pbf.varint();
142
+ const field = Math.floor(tag / 8);
143
+ if (field === 1) {
144
+ name = decoder.decode(pbf.bytes());
145
+ }
146
+ else if (field === 2) {
147
+ const inner = new Pbf(pbf.bytes());
148
+ const feature = { tags: [], type: 0, geometry: [] };
149
+ while (inner.pos < inner.end) {
150
+ const t = inner.varint();
151
+ const f = Math.floor(t / 8);
152
+ if (f === 2) {
153
+ feature.tags = inner.packed();
154
+ }
155
+ else if (f === 3) {
156
+ feature.type = inner.varint();
157
+ }
158
+ else if (f === 4) {
159
+ feature.geometry = inner.packed();
160
+ }
161
+ else {
162
+ inner.skip(t & 7);
163
+ }
164
+ }
165
+ raw.push(feature);
166
+ }
167
+ else if (field === 3) {
168
+ keys.push(decoder.decode(pbf.bytes()));
169
+ }
170
+ else if (field === 4) {
171
+ values.push(value(pbf.bytes()));
172
+ }
173
+ else if (field === 5) {
174
+ extent = pbf.varint();
175
+ }
176
+ else {
177
+ pbf.skip(tag & 7);
178
+ }
179
+ }
180
+ const features = [];
181
+ for (const each of raw) {
182
+ if (each.type < 1 || each.type > 3) {
183
+ continue;
184
+ }
185
+ const properties = {};
186
+ for (let i = 0; i + 1 < each.tags.length; i += 2) {
187
+ const key = keys[each.tags[i]];
188
+ if (key !== undefined) {
189
+ properties[key] = values[each.tags[i + 1]];
190
+ }
191
+ }
192
+ features.push({ type: each.type, properties, geometry: geometry(each.geometry, each.type) });
193
+ }
194
+ return { name, extent, features };
195
+ }
196
+ var GeoMvt;
197
+ (function (GeoMvt) {
198
+ /** The layers of a tile, by name. */
199
+ function decode(bytes) {
200
+ const pbf = new Pbf(bytes);
201
+ const layers = new Map();
202
+ while (pbf.pos < pbf.end) {
203
+ const tag = pbf.varint();
204
+ if (Math.floor(tag / 8) === 3) {
205
+ const made = layer(pbf.bytes());
206
+ layers.set(made.name, made);
207
+ }
208
+ else {
209
+ pbf.skip(tag & 7);
210
+ }
211
+ }
212
+ return layers;
213
+ }
214
+ GeoMvt.decode = decode;
215
+ })(GeoMvt || (exports.GeoMvt = GeoMvt = {}));
216
+ //# sourceMappingURL=geo-mvt.js.map
@@ -0,0 +1,28 @@
1
+ import type { MvtLayer } from './geo-mvt';
2
+ export declare const MapPixel: {
3
+ readonly LAND: 0;
4
+ readonly WATER: 1;
5
+ readonly WOOD: 2;
6
+ readonly GRASS: 3;
7
+ readonly SAND: 4;
8
+ readonly ICE: 5;
9
+ readonly TOWN: 6;
10
+ readonly ROAD: 7;
11
+ readonly MAJOR: 8;
12
+ };
13
+ export type MapPixelKind = (typeof MapPixel)[keyof typeof MapPixel];
14
+ /** A name on a tile: where (fractions of the tile), and how much it matters (`rank`, lower the more; a capital 0). */
15
+ export interface MapName {
16
+ name: string;
17
+ x: number;
18
+ y: number;
19
+ rank: number;
20
+ kind: string;
21
+ }
22
+ export declare namespace GeoPixels {
23
+ /** The pixels of a tile: `zoom` the zoom it is of (towns from 9, motorways from 9, the smaller roads from 11). */
24
+ function tile(layers: ReadonlyMap<string, MvtLayer> | undefined, zoom: number, size?: number): Uint8Array;
25
+ /** The names of the places on a tile, in `language` where the map has it (`name:zh`), the most important first. */
26
+ function names(layers: ReadonlyMap<string, MvtLayer> | undefined, language: string): MapName[];
27
+ }
28
+ //# sourceMappingURL=geo-pixels.d.ts.map
@@ -0,0 +1,141 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.GeoPixels = exports.MapPixel = void 0;
4
+ const geo_raster_1 = require("./geo-raster");
5
+ // A map tile as pixels (GeoPixels), for a map drawn as pixel art at any zoom: what covers each of its size × size
6
+ // pixels (land, water, woods, sand, ice, towns, roads) from the layers of a vector tile in the schema of OpenMapTiles,
7
+ // and the names of the places on it, where they are. A tile the map has nothing of is the open sea.
8
+ exports.MapPixel = {
9
+ LAND: 0,
10
+ WATER: 1,
11
+ WOOD: 2,
12
+ GRASS: 3,
13
+ SAND: 4,
14
+ ICE: 5,
15
+ TOWN: 6,
16
+ ROAD: 7,
17
+ MAJOR: 8,
18
+ };
19
+ const COVER = {
20
+ wood: exports.MapPixel.WOOD,
21
+ forest: exports.MapPixel.WOOD,
22
+ grass: exports.MapPixel.GRASS,
23
+ farmland: exports.MapPixel.GRASS,
24
+ wetland: exports.MapPixel.GRASS,
25
+ sand: exports.MapPixel.SAND,
26
+ beach: exports.MapPixel.SAND,
27
+ ice: exports.MapPixel.ICE,
28
+ glacier: exports.MapPixel.ICE,
29
+ };
30
+ const TOWNS = new Set(['residential', 'commercial', 'industrial', 'retail', 'suburb', 'neighbourhood', 'quarter']);
31
+ const MAJOR = new Set(['motorway', 'trunk']);
32
+ const ROADS = new Set(['primary', 'secondary']);
33
+ const PLACES = { continent: -2, country: -1, state: 1, city: 2, town: 4, village: 6, suburb: 7 };
34
+ /** Names in a script of their own, by the start of a language tag. */
35
+ const NAME_SCRIPTS = [
36
+ ['zh-tw', ['name:zh-Hant']],
37
+ ['zh-hk', ['name:zh-Hant']],
38
+ ['zh-hant', ['name:zh-Hant']],
39
+ ['zh', ['name:zh-Hans']],
40
+ ];
41
+ var GeoPixels;
42
+ (function (GeoPixels) {
43
+ /** The pixels of a tile: `zoom` the zoom it is of (towns from 9, motorways from 9, the smaller roads from 11). */
44
+ function tile(layers, zoom, size = 64) {
45
+ const out = new Uint8Array(size * size);
46
+ if (!layers) {
47
+ return out.fill(exports.MapPixel.WATER);
48
+ }
49
+ const each = (name, run) => {
50
+ const layer = layers.get(name);
51
+ if (!layer) {
52
+ return;
53
+ }
54
+ const scale = size / layer.extent;
55
+ for (const feature of layer.features) {
56
+ run(feature.type, feature.properties, feature.geometry.map(part => part.map(([u, v]) => [u * scale, v * scale])));
57
+ }
58
+ };
59
+ const set = (kind) => (index) => {
60
+ out[index] = kind;
61
+ };
62
+ each('landcover', (type, properties, parts) => {
63
+ var _a;
64
+ const kind = (_a = COVER[String(properties.class)]) !== null && _a !== void 0 ? _a : COVER[String(properties.subclass)];
65
+ if (kind !== undefined && type === 3) {
66
+ geo_raster_1.GeoRaster.fill(parts, size, set(kind));
67
+ }
68
+ });
69
+ if (zoom >= 9) {
70
+ each('landuse', (type, properties, parts) => {
71
+ if (type === 3 && TOWNS.has(String(properties.class))) {
72
+ geo_raster_1.GeoRaster.fill(parts, size, set(exports.MapPixel.TOWN));
73
+ }
74
+ });
75
+ }
76
+ each('park', (type, _properties, parts) => {
77
+ if (type === 3 && zoom >= 8) {
78
+ geo_raster_1.GeoRaster.fill(parts, size, set(exports.MapPixel.WOOD));
79
+ }
80
+ });
81
+ each('water', (type, _properties, parts) => {
82
+ if (type === 3) {
83
+ geo_raster_1.GeoRaster.fill(parts, size, set(exports.MapPixel.WATER));
84
+ }
85
+ });
86
+ if (zoom >= 8) {
87
+ each('waterway', (type, properties, parts) => {
88
+ if (type === 2 && (properties.class === 'river' || zoom >= 12)) {
89
+ for (const line of parts) {
90
+ geo_raster_1.GeoRaster.stroke(line, 1, size, set(exports.MapPixel.WATER));
91
+ }
92
+ }
93
+ });
94
+ }
95
+ if (zoom >= 9) {
96
+ each('transportation', (type, properties, parts) => {
97
+ const kind = String(properties.class);
98
+ const major = MAJOR.has(kind);
99
+ if (type !== 2 || properties.brunnel === 'tunnel' || !(major || (zoom >= 11 && ROADS.has(kind)) || (zoom >= 13 && kind === 'tertiary'))) {
100
+ return;
101
+ }
102
+ for (const line of parts) {
103
+ geo_raster_1.GeoRaster.stroke(line, 1, size, set(major ? exports.MapPixel.MAJOR : exports.MapPixel.ROAD));
104
+ }
105
+ });
106
+ }
107
+ return out;
108
+ }
109
+ GeoPixels.tile = tile;
110
+ /** The names of the places on a tile, in `language` where the map has it (`name:zh`), the most important first. */
111
+ function names(layers, language) {
112
+ var _a, _b;
113
+ var _c;
114
+ const layer = layers === null || layers === void 0 ? void 0 : layers.get('place');
115
+ if (!layer) {
116
+ return [];
117
+ }
118
+ // The keys of names the map has for a language (OpenMapTiles): its own script first, then the language.
119
+ const lower = language.toLowerCase();
120
+ const script = (_c = (_a = NAME_SCRIPTS.find(([prefix]) => lower.startsWith(prefix))) === null || _a === void 0 ? void 0 : _a[1]) !== null && _c !== void 0 ? _c : [];
121
+ const keys = [...script, `name:${lower.slice(0, 2)}`];
122
+ const out = [];
123
+ for (const feature of layer.features) {
124
+ const point = (_b = feature.geometry[0]) === null || _b === void 0 ? void 0 : _b[0];
125
+ const kind = String(feature.properties.class);
126
+ const base = PLACES[kind];
127
+ if (feature.type !== 1 || !point || base === undefined) {
128
+ continue;
129
+ }
130
+ const name = [...keys, 'name'].map(key => feature.properties[key]).find(value => typeof value === 'string' && value.trim());
131
+ if (typeof name !== 'string') {
132
+ continue;
133
+ }
134
+ const rank = base + (Number(feature.properties.rank) || 5) / 10 + (feature.properties.capital === 2 ? -1 : 0);
135
+ out.push({ name: name.trim(), x: point[0] / layer.extent, y: point[1] / layer.extent, rank, kind });
136
+ }
137
+ return out.sort((a, b) => a.rank - b.rank);
138
+ }
139
+ GeoPixels.names = names;
140
+ })(GeoPixels || (exports.GeoPixels = GeoPixels = {}));
141
+ //# sourceMappingURL=geo-pixels.js.map
@@ -0,0 +1,15 @@
1
+ import type { LonLat } from './geo-grid';
2
+ import type { Fetcher } from './geo-tiles';
3
+ export interface GeoPlace extends LonLat {
4
+ name: string;
5
+ /** Where it is: the rest of its address. */
6
+ detail: string;
7
+ }
8
+ export declare namespace GeoPlaces {
9
+ function search(query: string, language: string, fetcher?: Fetcher): Promise<GeoPlace[]>;
10
+ /** What a place is called: the name of what is there, or its street; none if the search knows nothing. */
11
+ function name(place: LonLat, language: string, fetcher?: Fetcher): Promise<GeoPlace | undefined>;
12
+ /** Where the device is, if the user lets the page know. */
13
+ function here(timeout?: number): Promise<LonLat>;
14
+ }
15
+ //# sourceMappingURL=geo-places.d.ts.map
@@ -0,0 +1,74 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.GeoPlaces = void 0;
4
+ var GeoPlaces;
5
+ (function (GeoPlaces) {
6
+ async function search(query, language, fetcher = (url, init) => fetch(url, init)) {
7
+ const text = query.trim();
8
+ if (!text) {
9
+ return [];
10
+ }
11
+ const url = `https://nominatim.openstreetmap.org/search?format=jsonv2&limit=6&q=${encodeURIComponent(text)}&accept-language=${encodeURIComponent(language)}`;
12
+ const response = await fetcher(url, { headers: { Accept: 'application/json' } });
13
+ if (!response.ok) {
14
+ throw new Error(`Search: HTTP ${response.status}`);
15
+ }
16
+ const found = (await response.json());
17
+ return found
18
+ .map(each => {
19
+ var _a;
20
+ const lat = Number(each.lat);
21
+ const lon = Number(each.lon);
22
+ const whole = (_a = each.display_name) !== null && _a !== void 0 ? _a : '';
23
+ const name = each.name || whole.split(',')[0] || text;
24
+ const detail = whole
25
+ .split(',')
26
+ .slice(1)
27
+ .map(part => part.trim())
28
+ .filter(Boolean)
29
+ .slice(0, 3)
30
+ .join(', ');
31
+ return { lat, lon, name, detail };
32
+ })
33
+ .filter(each => Number.isFinite(each.lat) && Number.isFinite(each.lon));
34
+ }
35
+ GeoPlaces.search = search;
36
+ /** What a place is called: the name of what is there, or its street; none if the search knows nothing. */
37
+ async function name(place, language, fetcher = (url, init) => fetch(url, init)) {
38
+ var _a, _b, _c;
39
+ var _d, _e, _f;
40
+ const url = `https://nominatim.openstreetmap.org/reverse?format=jsonv2&zoom=17&lat=${place.lat}&lon=${place.lon}&accept-language=${encodeURIComponent(language)}`;
41
+ const response = await fetcher(url, { headers: { Accept: 'application/json' } });
42
+ if (!response.ok) {
43
+ return undefined;
44
+ }
45
+ const found = (await response.json());
46
+ const whole = (_d = found.display_name) !== null && _d !== void 0 ? _d : '';
47
+ const street = (_f = (_e = (_a = found.address) === null || _a === void 0 ? void 0 : _a.road) !== null && _e !== void 0 ? _e : (_b = found.address) === null || _b === void 0 ? void 0 : _b.neighbourhood) !== null && _f !== void 0 ? _f : (_c = found.address) === null || _c === void 0 ? void 0 : _c.suburb;
48
+ const called = found.name || street || whole.split(',')[0];
49
+ if (!called) {
50
+ return undefined;
51
+ }
52
+ const detail = whole
53
+ .split(',')
54
+ .map(part => part.trim())
55
+ .filter(part => part && part !== called)
56
+ .slice(0, 3)
57
+ .join(', ');
58
+ return { ...place, name: called, detail };
59
+ }
60
+ GeoPlaces.name = name;
61
+ /** Where the device is, if the user lets the page know. */
62
+ function here(timeout = 15000) {
63
+ return new Promise((resolve, reject) => {
64
+ const geo = typeof navigator === 'undefined' ? undefined : navigator.geolocation;
65
+ if (!geo) {
66
+ reject(new Error('location'));
67
+ return;
68
+ }
69
+ geo.getCurrentPosition(position => resolve({ lon: position.coords.longitude, lat: position.coords.latitude }), error => reject(new Error(error.message || 'location')), { enableHighAccuracy: false, timeout, maximumAge: 600000 });
70
+ });
71
+ }
72
+ GeoPlaces.here = here;
73
+ })(GeoPlaces || (exports.GeoPlaces = GeoPlaces = {}));
74
+ //# sourceMappingURL=geo-places.js.map
@@ -0,0 +1,57 @@
1
+ import type { MvtLayer } from './geo-mvt';
2
+ export declare const Ground: {
3
+ readonly LAND: 0;
4
+ readonly GRASS: 1;
5
+ readonly PARK: 2;
6
+ readonly WOOD: 3;
7
+ readonly FARM: 4;
8
+ readonly SAND: 5;
9
+ readonly WATER: 6;
10
+ readonly PAVED: 7;
11
+ readonly ROAD: 8;
12
+ readonly STREET: 9;
13
+ readonly PATH: 10;
14
+ readonly RAIL: 11;
15
+ readonly PITCH: 12;
16
+ };
17
+ export type GroundKind = (typeof Ground)[keyof typeof Ground];
18
+ export interface RasterBuilding {
19
+ /** Its top above the ground, and its bottom (a part on others, a bridge of a building), in metres. */
20
+ height: number;
21
+ min: number;
22
+ /** Its colour as the map has it (`#rrggbb`), if any. */
23
+ colour?: string;
24
+ /** How many columns of the plot it covers. */
25
+ area: number;
26
+ /** The middle of what it covers, in columns of the plot. */
27
+ x: number;
28
+ z: number;
29
+ }
30
+ export interface PlotRaster {
31
+ size: number;
32
+ /** The kind of ground of each column, by `z * size + x`. */
33
+ ground: Uint8Array;
34
+ /** The building on each column, by its index in `buildings` plus one; 0 none. */
35
+ building: Uint16Array;
36
+ buildings: RasterBuilding[];
37
+ }
38
+ /** Where in its tile a plot is: its corner and its side, fractions of the tile. */
39
+ export interface PlotWindow {
40
+ left: number;
41
+ top: number;
42
+ size: number;
43
+ }
44
+ type Ring = [number, number][];
45
+ export declare namespace GeoRaster {
46
+ /**
47
+ * The ground of a plot from the layers of the tile it is in: `window` where in the tile, `metres` the metres
48
+ * a column is across there (GeoGrid.metresPerColumn).
49
+ */
50
+ function plot(layers: ReadonlyMap<string, MvtLayer> | undefined, window: PlotWindow, metres: number): PlotRaster;
51
+ /** Runs `set` on each column whose middle is inside the rings (even-odd). */
52
+ function fill(rings: readonly Ring[], size: number, set: (index: number) => void): void;
53
+ /** Runs `set` on each column whose middle is within `width / 2` of the line. */
54
+ function stroke(line: Ring, width: number, size: number, set: (index: number) => void): void;
55
+ }
56
+ export {};
57
+ //# sourceMappingURL=geo-raster.d.ts.map