@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/README.en.md ADDED
@@ -0,0 +1,11 @@
1
+ # Cell - Ta Geo
2
+
3
+ Real places for Ta's extensions (a plain library, not a pi package), for any extension, not only games: nearby, trips, meeting in person, questions of geography.
4
+
5
+ - **A grid of plots over the earth** (`GeoGrid`): a tile of zoom 16 of Web Mercator is a plot of 256 × 256 columns, a column a pixel of zoom 24, so that every device names a place by the same numbers and what each makes fits beside the others' with nothing to agree on.
6
+ - **Vector tiles decoded** (`GeoMvt`): Mapbox Vector Tile v2, read without a library.
7
+ - **A source of tiles** (`OpenFreeMapTiles`): OpenStreetMap, free and without a key, under versions whose URLs never change.
8
+ - **Places** (`GeoPlaces`): a search of Nominatim, the name of a place, the location of the browser.
9
+ - **The ground of a plot** (`GeoRaster`): a kind of ground for each column and the buildings with their heights.
10
+
11
+ Map data © OpenStreetMap contributors: say so where it is shown (ODbL). The design is `docs/design/ta-earth.md`.
package/README.md CHANGED
@@ -1,3 +1,11 @@
1
- # Temporary Holding Version
1
+ # Cell - Ta Geo
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 给 Ta 的扩展用的真实地点库(普通的库,不是 pi 包)。和游戏无关的扩展也能用:附近、出行、线下见面、地理题。
4
+
5
+ - **全球地块网格**(`GeoGrid`):Web Mercator 第 16 级瓦片是一个地块,256 × 256 列;一列是第 24 级的一个像素。任何设备按同样的数字指同一个地方,拼起来不用协调。经纬度与列互换、地块号、所在的低级瓦片、每列多少米、把位置粗化到约 10 公里。
6
+ - **矢量瓦片解码**(`GeoMvt`):自带的 Mapbox Vector Tile v2 读取,不依赖第三方库。
7
+ - **瓦片来源**(`OpenFreeMapTiles`):OpenStreetMap 数据,免费、无需密钥;瓦片地址带版本,永不变,所以同一版本在每台设备上一样。版本下架时退回最新版。
8
+ - **地名搜索与定位**(`GeoPlaces`):Nominatim 搜索、反查地名,浏览器定位。
9
+ - **地面栅格化**(`GeoRaster`):把一个地块上的地物画成每列一种地面(草、公园、树林、水、道路……)和建筑(轮廓、高度、颜色)。
10
+
11
+ 地图数据 © OpenStreetMap 贡献者,使用时界面上要写出来(ODbL)。设计见 `docs/design/ta-earth.md`。
@@ -0,0 +1,50 @@
1
+ /** The zoom of a plot. */
2
+ export declare const PLOT_ZOOM = 16;
3
+ /** Columns across a plot. */
4
+ export declare const PLOT_SIZE = 256;
5
+ /** The zoom of a column: a pixel of a plot. */
6
+ export declare const COLUMN_ZOOM: number;
7
+ export interface LonLat {
8
+ lon: number;
9
+ lat: number;
10
+ }
11
+ /** A point of the grid, in columns: x east, z south, from the north-west corner of the earth. */
12
+ export interface GridPoint {
13
+ x: number;
14
+ z: number;
15
+ }
16
+ /** A plot: a tile of zoom 16. */
17
+ export interface Plot {
18
+ px: number;
19
+ pz: number;
20
+ }
21
+ /** A tile of a zoom of the maps of the web. */
22
+ export interface MapTile {
23
+ z: number;
24
+ x: number;
25
+ y: number;
26
+ }
27
+ export declare namespace GeoGrid {
28
+ /** Where a place is on the grid, in columns (not whole). */
29
+ function toGrid({ lon, lat }: LonLat): GridPoint;
30
+ /** The place at a point of the grid. */
31
+ function toLonLat({ x, z }: GridPoint): LonLat;
32
+ /** The plot a point is in. */
33
+ function plotOf({ x, z }: GridPoint): Plot;
34
+ /** A plot by its name, `16/x/y` as the maps of the web name its tile. */
35
+ function key({ px, pz }: Plot): string;
36
+ function parse(key: string): Plot | undefined;
37
+ /** The tile of a lower zoom the plot is in, and where in it, as a fraction of the tile (0 to 1). */
38
+ function tileOf({ px, pz }: Plot, zoom: number): {
39
+ tile: MapTile;
40
+ left: number;
41
+ top: number;
42
+ size: number;
43
+ };
44
+ /** The metres a column is across at a latitude. */
45
+ function metresPerColumn(lat: number): number;
46
+ /** The plots around one, `ring` away at most, nearest first. */
47
+ function around(plot: Plot, ring: number): Plot[];
48
+ /** A place made coarse: the middle of its tile of `zoom` (12: about ten kilometres), to tell others roughly where. */
49
+ function coarse(place: LonLat, zoom: number): LonLat;
50
+ }
@@ -0,0 +1,89 @@
1
+ // The earth as one grid (GeoGrid): Web Mercator, as the maps of the web draw it, cut into plots, the tiles of
2
+ // zoom 16, each of 256 × 256 columns. A column is a pixel of zoom 24, so that every device names the same place by
3
+ // the same numbers and what each makes of it fits beside what the others make, with nothing to agree on.
4
+ /** The zoom of a plot. */
5
+ export const PLOT_ZOOM = 16;
6
+ /** Columns across a plot. */
7
+ export const PLOT_SIZE = 256;
8
+ /** The zoom of a column: a pixel of a plot. */
9
+ export const COLUMN_ZOOM = PLOT_ZOOM + 8;
10
+ const COLUMNS = 2 ** COLUMN_ZOOM;
11
+ /** The earth's circumference at the equator, in metres (WGS 84). */
12
+ const EQUATOR = 40075016.686;
13
+ /** How far north and south Web Mercator goes. */
14
+ const MAX_LAT = 85.05112878;
15
+ export var GeoGrid;
16
+ (function (GeoGrid) {
17
+ /** Where a place is on the grid, in columns (not whole). */
18
+ function toGrid({ lon, lat }) {
19
+ const clamped = Math.max(-MAX_LAT, Math.min(MAX_LAT, lat));
20
+ const rad = (clamped * Math.PI) / 180;
21
+ const x = ((lon + 180) / 360) * COLUMNS;
22
+ const z = ((1 - Math.log(Math.tan(rad) + 1 / Math.cos(rad)) / Math.PI) / 2) * COLUMNS;
23
+ return { x, z };
24
+ }
25
+ GeoGrid.toGrid = toGrid;
26
+ /** The place at a point of the grid. */
27
+ function toLonLat({ x, z }) {
28
+ const lon = (x / COLUMNS) * 360 - 180;
29
+ const n = Math.PI - (2 * Math.PI * z) / COLUMNS;
30
+ const lat = (180 / Math.PI) * Math.atan(Math.sinh(n));
31
+ return { lon, lat };
32
+ }
33
+ GeoGrid.toLonLat = toLonLat;
34
+ /** The plot a point is in. */
35
+ function plotOf({ x, z }) {
36
+ return { px: Math.floor(x / PLOT_SIZE), pz: Math.floor(z / PLOT_SIZE) };
37
+ }
38
+ GeoGrid.plotOf = plotOf;
39
+ /** A plot by its name, `16/x/y` as the maps of the web name its tile. */
40
+ function key({ px, pz }) {
41
+ return `${PLOT_ZOOM}/${px}/${pz}`;
42
+ }
43
+ GeoGrid.key = key;
44
+ function parse(key) {
45
+ const match = /^16\/(\d+)\/(\d+)$/.exec(key);
46
+ if (!match) {
47
+ return undefined;
48
+ }
49
+ const plot = { px: Number(match[1]), pz: Number(match[2]) };
50
+ return plot.px < 2 ** PLOT_ZOOM && plot.pz < 2 ** PLOT_ZOOM ? plot : undefined;
51
+ }
52
+ GeoGrid.parse = parse;
53
+ /** The tile of a lower zoom the plot is in, and where in it, as a fraction of the tile (0 to 1). */
54
+ function tileOf({ px, pz }, zoom) {
55
+ const shift = PLOT_ZOOM - zoom;
56
+ const per = 2 ** shift;
57
+ return {
58
+ tile: { z: zoom, x: Math.floor(px / per), y: Math.floor(pz / per) },
59
+ left: (px % per) / per,
60
+ top: (pz % per) / per,
61
+ size: 1 / per,
62
+ };
63
+ }
64
+ GeoGrid.tileOf = tileOf;
65
+ /** The metres a column is across at a latitude. */
66
+ function metresPerColumn(lat) {
67
+ return (EQUATOR * Math.cos((lat * Math.PI) / 180)) / COLUMNS;
68
+ }
69
+ GeoGrid.metresPerColumn = metresPerColumn;
70
+ /** The plots around one, `ring` away at most, nearest first. */
71
+ function around(plot, ring) {
72
+ const out = [];
73
+ for (let dz = -ring; dz <= ring; dz++) {
74
+ for (let dx = -ring; dx <= ring; dx++) {
75
+ out.push({ px: plot.px + dx, pz: plot.pz + dz });
76
+ }
77
+ }
78
+ return out.sort((a, b) => Math.hypot(a.px - plot.px, a.pz - plot.pz) - Math.hypot(b.px - plot.px, b.pz - plot.pz));
79
+ }
80
+ GeoGrid.around = around;
81
+ /** A place made coarse: the middle of its tile of `zoom` (12: about ten kilometres), to tell others roughly where. */
82
+ function coarse(place, zoom) {
83
+ const per = 2 ** (COLUMN_ZOOM - zoom);
84
+ const { x, z } = toGrid(place);
85
+ return toLonLat({ x: (Math.floor(x / per) + 0.5) * per, z: (Math.floor(z / per) + 0.5) * per });
86
+ }
87
+ GeoGrid.coarse = coarse;
88
+ })(GeoGrid || (GeoGrid = {}));
89
+ //# sourceMappingURL=geo-grid.js.map
@@ -0,0 +1,17 @@
1
+ export type MvtValue = string | number | boolean;
2
+ export interface MvtFeature {
3
+ /** 1 a point, 2 a line, 3 a polygon. */
4
+ type: 1 | 2 | 3;
5
+ properties: Record<string, MvtValue>;
6
+ /** Points: one part of points; lines: a part each; polygons: rings, each outer one before its holes. */
7
+ geometry: [number, number][][];
8
+ }
9
+ export interface MvtLayer {
10
+ name: string;
11
+ extent: number;
12
+ features: MvtFeature[];
13
+ }
14
+ export declare namespace GeoMvt {
15
+ /** The layers of a tile, by name. */
16
+ function decode(bytes: Uint8Array): Map<string, MvtLayer>;
17
+ }
package/esm/geo-mvt.js ADDED
@@ -0,0 +1,213 @@
1
+ // Vector tiles (GeoMvt): the Mapbox Vector Tile format, version 2, that the maps of the web serve, read without a
2
+ // library: the protobuf of its layers, the keys and values of their features, the commands of their geometry made
3
+ // points, lines and rings in the units of the tile (0 to its extent).
4
+ /** Reads the protobuf of a tile: varints, fixed numbers and lengths of bytes. */
5
+ class Pbf {
6
+ constructor(buf, end = buf.length) {
7
+ this.buf = buf;
8
+ this.end = end;
9
+ this.pos = 0;
10
+ }
11
+ varint() {
12
+ let value = 0;
13
+ let shift = 0;
14
+ let byte;
15
+ do {
16
+ byte = this.buf[this.pos++];
17
+ value += (byte & 0x7f) * 2 ** shift;
18
+ shift += 7;
19
+ } while (byte & 0x80 && shift < 70);
20
+ return value;
21
+ }
22
+ svarint() {
23
+ const n = this.varint();
24
+ return n % 2 === 1 ? (n + 1) / -2 : n / 2;
25
+ }
26
+ bytes() {
27
+ const length = this.varint();
28
+ const start = this.pos;
29
+ this.pos += length;
30
+ return this.buf.subarray(start, start + length);
31
+ }
32
+ /** Skips a field of the wire type. */
33
+ skip(wire) {
34
+ if (wire === 0) {
35
+ this.varint();
36
+ }
37
+ else if (wire === 1) {
38
+ this.pos += 8;
39
+ }
40
+ else if (wire === 2) {
41
+ this.pos += this.varint();
42
+ }
43
+ else if (wire === 5) {
44
+ this.pos += 4;
45
+ }
46
+ else {
47
+ throw new Error(`Unknown wire type ${wire}`);
48
+ }
49
+ }
50
+ packed() {
51
+ const inner = new Pbf(this.bytes());
52
+ const out = [];
53
+ while (inner.pos < inner.end) {
54
+ out.push(inner.varint());
55
+ }
56
+ return out;
57
+ }
58
+ }
59
+ const decoder = new TextDecoder();
60
+ function value(bytes) {
61
+ const pbf = new Pbf(bytes);
62
+ let out = '';
63
+ while (pbf.pos < pbf.end) {
64
+ const tag = pbf.varint();
65
+ const field = Math.floor(tag / 8);
66
+ const view = new DataView(bytes.buffer, bytes.byteOffset + pbf.pos);
67
+ switch (field) {
68
+ case 1:
69
+ out = decoder.decode(pbf.bytes());
70
+ break;
71
+ case 2:
72
+ out = view.getFloat32(0, true);
73
+ pbf.pos += 4;
74
+ break;
75
+ case 3:
76
+ out = view.getFloat64(0, true);
77
+ pbf.pos += 8;
78
+ break;
79
+ case 4:
80
+ case 5:
81
+ out = pbf.varint();
82
+ break;
83
+ case 6:
84
+ out = pbf.svarint();
85
+ break;
86
+ case 7:
87
+ out = pbf.varint() !== 0;
88
+ break;
89
+ default:
90
+ pbf.skip(tag & 7);
91
+ }
92
+ }
93
+ return out;
94
+ }
95
+ /** The parts of a geometry from its commands: MoveTo starts a part, LineTo goes on, ClosePath closes a ring. */
96
+ function geometry(commands, type) {
97
+ const parts = [];
98
+ let part = [];
99
+ let x = 0;
100
+ let y = 0;
101
+ let i = 0;
102
+ const zigzag = (n) => (n % 2 === 1 ? (n + 1) / -2 : n / 2);
103
+ while (i < commands.length) {
104
+ const command = commands[i] & 7;
105
+ const count = commands[i] >>> 3;
106
+ i++;
107
+ if (command === 7) {
108
+ if (part.length > 0) {
109
+ part.push([part[0][0], part[0][1]]);
110
+ }
111
+ continue;
112
+ }
113
+ for (let k = 0; k < count && i + 1 < commands.length; k++) {
114
+ x += zigzag(commands[i++]);
115
+ y += zigzag(commands[i++]);
116
+ if (command === 1 && type !== 1) {
117
+ if (part.length > 0) {
118
+ parts.push(part);
119
+ }
120
+ part = [];
121
+ }
122
+ part.push([x, y]);
123
+ }
124
+ }
125
+ if (part.length > 0) {
126
+ parts.push(part);
127
+ }
128
+ return parts;
129
+ }
130
+ function layer(bytes) {
131
+ const pbf = new Pbf(bytes);
132
+ let name = '';
133
+ let extent = 4096;
134
+ const keys = [];
135
+ const values = [];
136
+ const raw = [];
137
+ while (pbf.pos < pbf.end) {
138
+ const tag = pbf.varint();
139
+ const field = Math.floor(tag / 8);
140
+ if (field === 1) {
141
+ name = decoder.decode(pbf.bytes());
142
+ }
143
+ else if (field === 2) {
144
+ const inner = new Pbf(pbf.bytes());
145
+ const feature = { tags: [], type: 0, geometry: [] };
146
+ while (inner.pos < inner.end) {
147
+ const t = inner.varint();
148
+ const f = Math.floor(t / 8);
149
+ if (f === 2) {
150
+ feature.tags = inner.packed();
151
+ }
152
+ else if (f === 3) {
153
+ feature.type = inner.varint();
154
+ }
155
+ else if (f === 4) {
156
+ feature.geometry = inner.packed();
157
+ }
158
+ else {
159
+ inner.skip(t & 7);
160
+ }
161
+ }
162
+ raw.push(feature);
163
+ }
164
+ else if (field === 3) {
165
+ keys.push(decoder.decode(pbf.bytes()));
166
+ }
167
+ else if (field === 4) {
168
+ values.push(value(pbf.bytes()));
169
+ }
170
+ else if (field === 5) {
171
+ extent = pbf.varint();
172
+ }
173
+ else {
174
+ pbf.skip(tag & 7);
175
+ }
176
+ }
177
+ const features = [];
178
+ for (const each of raw) {
179
+ if (each.type < 1 || each.type > 3) {
180
+ continue;
181
+ }
182
+ const properties = {};
183
+ for (let i = 0; i + 1 < each.tags.length; i += 2) {
184
+ const key = keys[each.tags[i]];
185
+ if (key !== undefined) {
186
+ properties[key] = values[each.tags[i + 1]];
187
+ }
188
+ }
189
+ features.push({ type: each.type, properties, geometry: geometry(each.geometry, each.type) });
190
+ }
191
+ return { name, extent, features };
192
+ }
193
+ export var GeoMvt;
194
+ (function (GeoMvt) {
195
+ /** The layers of a tile, by name. */
196
+ function decode(bytes) {
197
+ const pbf = new Pbf(bytes);
198
+ const layers = new Map();
199
+ while (pbf.pos < pbf.end) {
200
+ const tag = pbf.varint();
201
+ if (Math.floor(tag / 8) === 3) {
202
+ const made = layer(pbf.bytes());
203
+ layers.set(made.name, made);
204
+ }
205
+ else {
206
+ pbf.skip(tag & 7);
207
+ }
208
+ }
209
+ return layers;
210
+ }
211
+ GeoMvt.decode = decode;
212
+ })(GeoMvt || (GeoMvt = {}));
213
+ //# sourceMappingURL=geo-mvt.js.map
@@ -0,0 +1,27 @@
1
+ import type { MvtLayer } from './geo-mvt.js';
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
+ }
@@ -0,0 +1,138 @@
1
+ import { GeoRaster } from './geo-raster.js';
2
+ // A map tile as pixels (GeoPixels), for a map drawn as pixel art at any zoom: what covers each of its size × size
3
+ // pixels (land, water, woods, sand, ice, towns, roads) from the layers of a vector tile in the schema of OpenMapTiles,
4
+ // and the names of the places on it, where they are. A tile the map has nothing of is the open sea.
5
+ export const MapPixel = {
6
+ LAND: 0,
7
+ WATER: 1,
8
+ WOOD: 2,
9
+ GRASS: 3,
10
+ SAND: 4,
11
+ ICE: 5,
12
+ TOWN: 6,
13
+ ROAD: 7,
14
+ MAJOR: 8,
15
+ };
16
+ const COVER = {
17
+ wood: MapPixel.WOOD,
18
+ forest: MapPixel.WOOD,
19
+ grass: MapPixel.GRASS,
20
+ farmland: MapPixel.GRASS,
21
+ wetland: MapPixel.GRASS,
22
+ sand: MapPixel.SAND,
23
+ beach: MapPixel.SAND,
24
+ ice: MapPixel.ICE,
25
+ glacier: MapPixel.ICE,
26
+ };
27
+ const TOWNS = new Set(['residential', 'commercial', 'industrial', 'retail', 'suburb', 'neighbourhood', 'quarter']);
28
+ const MAJOR = new Set(['motorway', 'trunk']);
29
+ const ROADS = new Set(['primary', 'secondary']);
30
+ const PLACES = { continent: -2, country: -1, state: 1, city: 2, town: 4, village: 6, suburb: 7 };
31
+ /** Names in a script of their own, by the start of a language tag. */
32
+ const NAME_SCRIPTS = [
33
+ ['zh-tw', ['name:zh-Hant']],
34
+ ['zh-hk', ['name:zh-Hant']],
35
+ ['zh-hant', ['name:zh-Hant']],
36
+ ['zh', ['name:zh-Hans']],
37
+ ];
38
+ export var GeoPixels;
39
+ (function (GeoPixels) {
40
+ /** The pixels of a tile: `zoom` the zoom it is of (towns from 9, motorways from 9, the smaller roads from 11). */
41
+ function tile(layers, zoom, size = 64) {
42
+ const out = new Uint8Array(size * size);
43
+ if (!layers) {
44
+ return out.fill(MapPixel.WATER);
45
+ }
46
+ const each = (name, run) => {
47
+ const layer = layers.get(name);
48
+ if (!layer) {
49
+ return;
50
+ }
51
+ const scale = size / layer.extent;
52
+ for (const feature of layer.features) {
53
+ run(feature.type, feature.properties, feature.geometry.map(part => part.map(([u, v]) => [u * scale, v * scale])));
54
+ }
55
+ };
56
+ const set = (kind) => (index) => {
57
+ out[index] = kind;
58
+ };
59
+ each('landcover', (type, properties, parts) => {
60
+ var _a;
61
+ const kind = (_a = COVER[String(properties.class)]) !== null && _a !== void 0 ? _a : COVER[String(properties.subclass)];
62
+ if (kind !== undefined && type === 3) {
63
+ GeoRaster.fill(parts, size, set(kind));
64
+ }
65
+ });
66
+ if (zoom >= 9) {
67
+ each('landuse', (type, properties, parts) => {
68
+ if (type === 3 && TOWNS.has(String(properties.class))) {
69
+ GeoRaster.fill(parts, size, set(MapPixel.TOWN));
70
+ }
71
+ });
72
+ }
73
+ each('park', (type, _properties, parts) => {
74
+ if (type === 3 && zoom >= 8) {
75
+ GeoRaster.fill(parts, size, set(MapPixel.WOOD));
76
+ }
77
+ });
78
+ each('water', (type, _properties, parts) => {
79
+ if (type === 3) {
80
+ GeoRaster.fill(parts, size, set(MapPixel.WATER));
81
+ }
82
+ });
83
+ if (zoom >= 8) {
84
+ each('waterway', (type, properties, parts) => {
85
+ if (type === 2 && (properties.class === 'river' || zoom >= 12)) {
86
+ for (const line of parts) {
87
+ GeoRaster.stroke(line, 1, size, set(MapPixel.WATER));
88
+ }
89
+ }
90
+ });
91
+ }
92
+ if (zoom >= 9) {
93
+ each('transportation', (type, properties, parts) => {
94
+ const kind = String(properties.class);
95
+ const major = MAJOR.has(kind);
96
+ if (type !== 2 || properties.brunnel === 'tunnel' || !(major || (zoom >= 11 && ROADS.has(kind)) || (zoom >= 13 && kind === 'tertiary'))) {
97
+ return;
98
+ }
99
+ for (const line of parts) {
100
+ GeoRaster.stroke(line, 1, size, set(major ? MapPixel.MAJOR : MapPixel.ROAD));
101
+ }
102
+ });
103
+ }
104
+ return out;
105
+ }
106
+ GeoPixels.tile = tile;
107
+ /** The names of the places on a tile, in `language` where the map has it (`name:zh`), the most important first. */
108
+ function names(layers, language) {
109
+ var _a, _b;
110
+ var _c;
111
+ const layer = layers === null || layers === void 0 ? void 0 : layers.get('place');
112
+ if (!layer) {
113
+ return [];
114
+ }
115
+ // The keys of names the map has for a language (OpenMapTiles): its own script first, then the language.
116
+ const lower = language.toLowerCase();
117
+ const script = (_c = (_a = NAME_SCRIPTS.find(([prefix]) => lower.startsWith(prefix))) === null || _a === void 0 ? void 0 : _a[1]) !== null && _c !== void 0 ? _c : [];
118
+ const keys = [...script, `name:${lower.slice(0, 2)}`];
119
+ const out = [];
120
+ for (const feature of layer.features) {
121
+ const point = (_b = feature.geometry[0]) === null || _b === void 0 ? void 0 : _b[0];
122
+ const kind = String(feature.properties.class);
123
+ const base = PLACES[kind];
124
+ if (feature.type !== 1 || !point || base === undefined) {
125
+ continue;
126
+ }
127
+ const name = [...keys, 'name'].map(key => feature.properties[key]).find(value => typeof value === 'string' && value.trim());
128
+ if (typeof name !== 'string') {
129
+ continue;
130
+ }
131
+ const rank = base + (Number(feature.properties.rank) || 5) / 10 + (feature.properties.capital === 2 ? -1 : 0);
132
+ out.push({ name: name.trim(), x: point[0] / layer.extent, y: point[1] / layer.extent, rank, kind });
133
+ }
134
+ return out.sort((a, b) => a.rank - b.rank);
135
+ }
136
+ GeoPixels.names = names;
137
+ })(GeoPixels || (GeoPixels = {}));
138
+ //# sourceMappingURL=geo-pixels.js.map
@@ -0,0 +1,14 @@
1
+ import type { LonLat } from './geo-grid.js';
2
+ import type { Fetcher } from './geo-tiles.js';
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
+ }
@@ -0,0 +1,71 @@
1
+ export var GeoPlaces;
2
+ (function (GeoPlaces) {
3
+ async function search(query, language, fetcher = (url, init) => fetch(url, init)) {
4
+ const text = query.trim();
5
+ if (!text) {
6
+ return [];
7
+ }
8
+ const url = `https://nominatim.openstreetmap.org/search?format=jsonv2&limit=6&q=${encodeURIComponent(text)}&accept-language=${encodeURIComponent(language)}`;
9
+ const response = await fetcher(url, { headers: { Accept: 'application/json' } });
10
+ if (!response.ok) {
11
+ throw new Error(`Search: HTTP ${response.status}`);
12
+ }
13
+ const found = (await response.json());
14
+ return found
15
+ .map(each => {
16
+ var _a;
17
+ const lat = Number(each.lat);
18
+ const lon = Number(each.lon);
19
+ const whole = (_a = each.display_name) !== null && _a !== void 0 ? _a : '';
20
+ const name = each.name || whole.split(',')[0] || text;
21
+ const detail = whole
22
+ .split(',')
23
+ .slice(1)
24
+ .map(part => part.trim())
25
+ .filter(Boolean)
26
+ .slice(0, 3)
27
+ .join(', ');
28
+ return { lat, lon, name, detail };
29
+ })
30
+ .filter(each => Number.isFinite(each.lat) && Number.isFinite(each.lon));
31
+ }
32
+ GeoPlaces.search = search;
33
+ /** What a place is called: the name of what is there, or its street; none if the search knows nothing. */
34
+ async function name(place, language, fetcher = (url, init) => fetch(url, init)) {
35
+ var _a, _b, _c;
36
+ var _d, _e, _f;
37
+ const url = `https://nominatim.openstreetmap.org/reverse?format=jsonv2&zoom=17&lat=${place.lat}&lon=${place.lon}&accept-language=${encodeURIComponent(language)}`;
38
+ const response = await fetcher(url, { headers: { Accept: 'application/json' } });
39
+ if (!response.ok) {
40
+ return undefined;
41
+ }
42
+ const found = (await response.json());
43
+ const whole = (_d = found.display_name) !== null && _d !== void 0 ? _d : '';
44
+ 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;
45
+ const called = found.name || street || whole.split(',')[0];
46
+ if (!called) {
47
+ return undefined;
48
+ }
49
+ const detail = whole
50
+ .split(',')
51
+ .map(part => part.trim())
52
+ .filter(part => part && part !== called)
53
+ .slice(0, 3)
54
+ .join(', ');
55
+ return { ...place, name: called, detail };
56
+ }
57
+ GeoPlaces.name = name;
58
+ /** Where the device is, if the user lets the page know. */
59
+ function here(timeout = 15000) {
60
+ return new Promise((resolve, reject) => {
61
+ const geo = typeof navigator === 'undefined' ? undefined : navigator.geolocation;
62
+ if (!geo) {
63
+ reject(new Error('location'));
64
+ return;
65
+ }
66
+ geo.getCurrentPosition(position => resolve({ lon: position.coords.longitude, lat: position.coords.latitude }), error => reject(new Error(error.message || 'location')), { enableHighAccuracy: false, timeout, maximumAge: 600000 });
67
+ });
68
+ }
69
+ GeoPlaces.here = here;
70
+ })(GeoPlaces || (GeoPlaces = {}));
71
+ //# sourceMappingURL=geo-places.js.map