@duoquote/geotini 0.0.0-stage → 0.1.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/CHANGELOG.md +88 -0
- package/LICENSE +21 -0
- package/README.md +331 -2
- package/package.json +126 -4
- package/src/deckgl.js +120 -0
- package/src/error.js +16 -0
- package/src/geoindex.js +373 -0
- package/src/geotini.js +3169 -0
- package/src/google.js +113 -0
- package/src/leaflet.js +82 -0
- package/src/mapbox.js +8 -0
- package/src/maplibre.js +74 -0
- package/src/mongodb.js +179 -0
- package/src/openlayers.js +69 -0
- package/src/redis.js +217 -0
- package/src/reference.js +1463 -0
- package/src/turf.js +79 -0
- package/types/deckgl.d.ts +53 -0
- package/types/google.d.ts +57 -0
- package/types/index.d.ts +453 -0
- package/types/leaflet.d.ts +56 -0
- package/types/mapbox.d.ts +29 -0
- package/types/maplibre.d.ts +53 -0
- package/types/mongodb.d.ts +108 -0
- package/types/openlayers.d.ts +39 -0
- package/types/redis.d.ts +117 -0
- package/types/reference.d.ts +133 -0
- package/types/turf.d.ts +59 -0
package/package.json
CHANGED
|
@@ -1,6 +1,128 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@duoquote/geotini",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "A compact, URL-safe text encoding for whole GeoJSON geometries: points, lines, polygons with holes, multi-geometries and collections, with optional Z and M. Lossless at the precision you pick, and no dependencies.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"geojson",
|
|
7
|
+
"geometry",
|
|
8
|
+
"encoding",
|
|
9
|
+
"compression",
|
|
10
|
+
"polygon",
|
|
11
|
+
"multipolygon",
|
|
12
|
+
"polyline",
|
|
13
|
+
"encoded polyline",
|
|
14
|
+
"base64url",
|
|
15
|
+
"url-safe",
|
|
16
|
+
"share link",
|
|
17
|
+
"qr code",
|
|
18
|
+
"twkb",
|
|
19
|
+
"gis",
|
|
20
|
+
"geospatial",
|
|
21
|
+
"maps",
|
|
22
|
+
"leaflet",
|
|
23
|
+
"maplibre",
|
|
24
|
+
"mapbox",
|
|
25
|
+
"openlayers",
|
|
26
|
+
"deck.gl",
|
|
27
|
+
"turf",
|
|
28
|
+
"google maps",
|
|
29
|
+
"mongodb",
|
|
30
|
+
"redis",
|
|
31
|
+
"bun",
|
|
32
|
+
"deno",
|
|
33
|
+
"typescript",
|
|
34
|
+
"zero dependencies"
|
|
35
|
+
],
|
|
36
|
+
"license": "MIT",
|
|
37
|
+
"author": "Güven Değirmenci",
|
|
38
|
+
"homepage": "https://github.com/Duoquote/geotini/tree/main/src/js#readme",
|
|
39
|
+
"repository": {
|
|
40
|
+
"type": "git",
|
|
41
|
+
"url": "git+https://github.com/Duoquote/geotini.git",
|
|
42
|
+
"directory": "src/js"
|
|
43
|
+
},
|
|
44
|
+
"bugs": "https://github.com/Duoquote/geotini/issues",
|
|
45
|
+
"type": "module",
|
|
46
|
+
"sideEffects": false,
|
|
47
|
+
"exports": {
|
|
48
|
+
".": {
|
|
49
|
+
"types": "./types/index.d.ts",
|
|
50
|
+
"default": "./src/geotini.js"
|
|
51
|
+
},
|
|
52
|
+
"./reference": {
|
|
53
|
+
"types": "./types/reference.d.ts",
|
|
54
|
+
"default": "./src/reference.js"
|
|
55
|
+
},
|
|
56
|
+
"./leaflet": {
|
|
57
|
+
"types": "./types/leaflet.d.ts",
|
|
58
|
+
"default": "./src/leaflet.js"
|
|
59
|
+
},
|
|
60
|
+
"./maplibre": {
|
|
61
|
+
"types": "./types/maplibre.d.ts",
|
|
62
|
+
"default": "./src/maplibre.js"
|
|
63
|
+
},
|
|
64
|
+
"./mapbox": {
|
|
65
|
+
"types": "./types/mapbox.d.ts",
|
|
66
|
+
"default": "./src/mapbox.js"
|
|
67
|
+
},
|
|
68
|
+
"./openlayers": {
|
|
69
|
+
"types": "./types/openlayers.d.ts",
|
|
70
|
+
"default": "./src/openlayers.js"
|
|
71
|
+
},
|
|
72
|
+
"./deckgl": {
|
|
73
|
+
"types": "./types/deckgl.d.ts",
|
|
74
|
+
"default": "./src/deckgl.js"
|
|
75
|
+
},
|
|
76
|
+
"./turf": {
|
|
77
|
+
"types": "./types/turf.d.ts",
|
|
78
|
+
"default": "./src/turf.js"
|
|
79
|
+
},
|
|
80
|
+
"./google": {
|
|
81
|
+
"types": "./types/google.d.ts",
|
|
82
|
+
"default": "./src/google.js"
|
|
83
|
+
},
|
|
84
|
+
"./mongodb": {
|
|
85
|
+
"types": "./types/mongodb.d.ts",
|
|
86
|
+
"default": "./src/mongodb.js"
|
|
87
|
+
},
|
|
88
|
+
"./redis": {
|
|
89
|
+
"types": "./types/redis.d.ts",
|
|
90
|
+
"default": "./src/redis.js"
|
|
91
|
+
},
|
|
92
|
+
"./package.json": "./package.json"
|
|
93
|
+
},
|
|
94
|
+
"main": "./src/geotini.js",
|
|
95
|
+
"types": "./types/index.d.ts",
|
|
96
|
+
"files": [
|
|
97
|
+
"src",
|
|
98
|
+
"types",
|
|
99
|
+
"CHANGELOG.md"
|
|
100
|
+
],
|
|
101
|
+
"engines": {
|
|
102
|
+
"node": ">=22"
|
|
103
|
+
},
|
|
104
|
+
"publishConfig": {
|
|
105
|
+
"access": "public"
|
|
106
|
+
},
|
|
107
|
+
"scripts": {
|
|
108
|
+
"test": "node test/run.js",
|
|
109
|
+
"test:bun": "bun test/run.js",
|
|
110
|
+
"test:deno": "deno run -A test/run.js",
|
|
111
|
+
"size": "node scripts/size.js",
|
|
112
|
+
"check:deps": "node scripts/check-deps.js",
|
|
113
|
+
"test:types": "tsc -p test/types"
|
|
114
|
+
},
|
|
115
|
+
"devDependencies": {
|
|
116
|
+
"@deck.gl/core": "^9.4.2",
|
|
117
|
+
"@deck.gl/layers": "^9.4.2",
|
|
118
|
+
"@duoquote/polytini": "^0.1.13",
|
|
119
|
+
"@maplibre/maplibre-gl-style-spec": "^27.0.0",
|
|
120
|
+
"@turf/turf": "^7.5.1",
|
|
121
|
+
"esbuild": "^0.28.2",
|
|
122
|
+
"jsdom": "^29.1.1",
|
|
123
|
+
"leaflet": "^1.9.4",
|
|
124
|
+
"leaflet-2": "npm:leaflet@^2.0.0-beta.5",
|
|
125
|
+
"ol": "^10.11.0",
|
|
126
|
+
"typescript": "^7.0.2"
|
|
127
|
+
}
|
|
128
|
+
}
|
package/src/deckgl.js
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
// deck.gl: geotini strings as layer data.
|
|
2
|
+
//
|
|
3
|
+
// import { GeoJsonLayer, PathLayer, SolidPolygonLayer } from '@deck.gl/layers';
|
|
4
|
+
// import { geotiniData, binaryPaths, flatPolygons } from '@duoquote/geotini/deckgl';
|
|
5
|
+
// new GeoJsonLayer({ id: 'all', data: geotiniData(strings) }); // every type
|
|
6
|
+
// new PathLayer({ id: 'lines', data: binaryPaths(strings), _pathType: 'open' });
|
|
7
|
+
// new SolidPolygonLayer({ id: 'fill', data: flatPolygons(strings), getPolygon: (d) => d, positionFormat: 'XY' });
|
|
8
|
+
//
|
|
9
|
+
// geotiniData is a GeoJSON FeatureCollection, which GeoJsonLayer draws
|
|
10
|
+
// whatever the types. binaryPaths is deck.gl's binary format for PathLayer
|
|
11
|
+
// (and TripsLayer): one typed array for every vertex, no array per point.
|
|
12
|
+
// flatPolygons gives each polygon as deck.gl's flat polygon,
|
|
13
|
+
// { positions, holeIndices }, which SolidPolygonLayer and PolygonLayer
|
|
14
|
+
// read with holes; the binary polygon format has no holes. No deck.gl code
|
|
15
|
+
// is imported.
|
|
16
|
+
/* @ts-self-types="../types/deckgl.d.ts" */
|
|
17
|
+
import { decode } from './geotini.js';
|
|
18
|
+
import { toFeatureCollection } from './turf.js';
|
|
19
|
+
|
|
20
|
+
const list = (encoded) => {
|
|
21
|
+
if (typeof encoded == 'string') return [encoded];
|
|
22
|
+
if (!Array.isArray(encoded)) throw new TypeError('Expected a geotini string or an array of them');
|
|
23
|
+
return encoded;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
/** A FeatureCollection for GeoJsonLayer, one Feature per string. Options: `properties`, `id`, `bbox` and decode's. */
|
|
27
|
+
export const geotiniData = (encoded, options) => toFeatureCollection(encoded, options);
|
|
28
|
+
|
|
29
|
+
// Every line and ring of a geometry, in order; points are skipped.
|
|
30
|
+
function paths(g, out) {
|
|
31
|
+
switch (g.type) {
|
|
32
|
+
case 'LineString':
|
|
33
|
+
if (g.coordinates.length) out.push(g.coordinates);
|
|
34
|
+
return;
|
|
35
|
+
case 'MultiLineString':
|
|
36
|
+
case 'Polygon':
|
|
37
|
+
for (const c of g.coordinates) if (c.length) out.push(c);
|
|
38
|
+
return;
|
|
39
|
+
case 'MultiPolygon':
|
|
40
|
+
for (const p of g.coordinates) for (const c of p) if (c.length) out.push(c);
|
|
41
|
+
return;
|
|
42
|
+
case 'GeometryCollection':
|
|
43
|
+
for (const m of g.geometries) paths(m, out);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const sizeOf = (o) => (o?.z ? 3 : 2);
|
|
48
|
+
const Float = (o) => (o?.float32 ? Float32Array : Float64Array);
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* deck.gl binary data for PathLayer: one path per line of every string
|
|
52
|
+
* (each part of a MultiLineString, each ring of a polygon, as its outline),
|
|
53
|
+
* `[lng, lat]` per vertex, or `[lng, lat, z]` with `{ z: true }`. Points are
|
|
54
|
+
* skipped. `featureIds` has the index of the string each path came from.
|
|
55
|
+
* Options: `z` and `float32` (Float32Array instead of Float64Array), and
|
|
56
|
+
* decode's `checksum`, `maxLength` and `maxPositions`, for each string.
|
|
57
|
+
*/
|
|
58
|
+
export function binaryPaths(encoded, options) {
|
|
59
|
+
const all = [], featureIds = [], size = sizeOf(options);
|
|
60
|
+
list(encoded).forEach((s, i) => {
|
|
61
|
+
const before = all.length;
|
|
62
|
+
paths(decode(s, options), all);
|
|
63
|
+
for (let k = before; k < all.length; k++) featureIds.push(i);
|
|
64
|
+
});
|
|
65
|
+
let n = 0;
|
|
66
|
+
for (const p of all) n += p.length;
|
|
67
|
+
const value = new (Float(options))(n * size), startIndices = new Uint32Array(all.length + 1);
|
|
68
|
+
let k = 0;
|
|
69
|
+
all.forEach((p, i) => {
|
|
70
|
+
startIndices[i] = k;
|
|
71
|
+
for (const pos of p) {
|
|
72
|
+
value[k * size] = pos[0];
|
|
73
|
+
value[k * size + 1] = pos[1];
|
|
74
|
+
if (size == 3) value[k * size + 2] = pos[2] ?? 0;
|
|
75
|
+
k++;
|
|
76
|
+
}
|
|
77
|
+
});
|
|
78
|
+
startIndices[all.length] = k;
|
|
79
|
+
return { length: all.length, startIndices, attributes: { getPath: { value, size } }, featureIds: Uint32Array.from(featureIds) };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Each polygon of every string as deck.gl's flat polygon:
|
|
84
|
+
* `{ positions, holeIndices, featureId }`, where `positions` has every
|
|
85
|
+
* ring's vertices in one typed array, `holeIndices` the offset (in values)
|
|
86
|
+
* where each hole starts, and `featureId` the index of the string. A
|
|
87
|
+
* MultiPolygon gives one entry per polygon. Lines and points are skipped.
|
|
88
|
+
* For SolidPolygonLayer or PolygonLayer with `getPolygon: (d) => d` and
|
|
89
|
+
* `positionFormat: 'XY'` (or 'XYZ' with `{ z: true }`). Options: `z`,
|
|
90
|
+
* `float32` and decode's, as for binaryPaths.
|
|
91
|
+
*/
|
|
92
|
+
export function flatPolygons(encoded, options) {
|
|
93
|
+
const out = [], size = sizeOf(options), F = Float(options);
|
|
94
|
+
const polygon = (rings, featureId) => {
|
|
95
|
+
rings = rings.filter((r) => r.length);
|
|
96
|
+
if (!rings.length) return;
|
|
97
|
+
let n = 0;
|
|
98
|
+
for (const r of rings) n += r.length;
|
|
99
|
+
const positions = new F(n * size), holeIndices = [];
|
|
100
|
+
let k = 0;
|
|
101
|
+
rings.forEach((r, i) => {
|
|
102
|
+
if (i > 0) holeIndices.push(k * size);
|
|
103
|
+
for (const pos of r) {
|
|
104
|
+
positions[k * size] = pos[0];
|
|
105
|
+
positions[k * size + 1] = pos[1];
|
|
106
|
+
if (size == 3) positions[k * size + 2] = pos[2] ?? 0;
|
|
107
|
+
k++;
|
|
108
|
+
}
|
|
109
|
+
});
|
|
110
|
+
out.push(holeIndices.length ? { positions, holeIndices, featureId } : { positions, featureId });
|
|
111
|
+
};
|
|
112
|
+
const walk = (g, i) => {
|
|
113
|
+
if (g.type == 'Polygon') polygon(g.coordinates, i);
|
|
114
|
+
else if (g.type == 'MultiPolygon') for (const p of g.coordinates) polygon(p, i);
|
|
115
|
+
else if (g.type == 'GeometryCollection') for (const m of g.geometries) walk(m, i);
|
|
116
|
+
};
|
|
117
|
+
list(encoded).forEach((s, i) => walk(decode(s, options), i));
|
|
118
|
+
return out;
|
|
119
|
+
}
|
|
120
|
+
|
package/src/error.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// The error both codecs throw for a string they refuse. It has its own
|
|
2
|
+
// module so that @duoquote/geotini and @duoquote/geotini/reference throw the
|
|
3
|
+
// same class, and `instanceof GeotiniError` works whichever one decoded.
|
|
4
|
+
//
|
|
5
|
+
// `code` is one of the stable codes in SPEC.md section 14: TRUNCATED,
|
|
6
|
+
// BAD_CHARACTER, UNSUPPORTED_VERSION, BAD_HEADER, NON_CANONICAL, CHECKSUM,
|
|
7
|
+
// COUNT_TOO_LARGE, OUT_OF_RANGE, EMPTY_CLOSED_PATH, TOO_DEEP and
|
|
8
|
+
// TRAILING_DATA, plus WRONG_TYPE from decodeLine and LIMIT_EXCEEDED for a
|
|
9
|
+
// string that's longer, or holds more, than the decoder was told to take.
|
|
10
|
+
export class GeotiniError extends Error {
|
|
11
|
+
constructor(code, message) {
|
|
12
|
+
super(message || 'Invalid geotini string: ' + code);
|
|
13
|
+
this.name = 'GeotiniError';
|
|
14
|
+
this.code = code;
|
|
15
|
+
}
|
|
16
|
+
}
|
package/src/geoindex.js
ADDED
|
@@ -0,0 +1,373 @@
|
|
|
1
|
+
// What the database adapters (/mongodb and /redis) index in place of a whole
|
|
2
|
+
// geometry: its bounds on the sphere, a polygon that covers them and that
|
|
3
|
+
// MongoDB's 2dsphere index accepts, and a representative point. Internal:
|
|
4
|
+
// not an entry of its own. src/python/geotini/_geoindex.py is the same code
|
|
5
|
+
// in Python, and integrations/mongodb checks that the two agree.
|
|
6
|
+
//
|
|
7
|
+
// MongoDB and Redis read a geometry on the sphere: an edge is the shorter
|
|
8
|
+
// great-circle arc between its two positions. So the bounds here cover each
|
|
9
|
+
// edge as a great circle (which bulges toward a pole) and as a straight line
|
|
10
|
+
// in longitude and latitude (which stays inside the box of its ends), and
|
|
11
|
+
// the covering polygon's own edges are placed so that, read as great
|
|
12
|
+
// circles, they still contain that box.
|
|
13
|
+
|
|
14
|
+
const RAD = Math.PI / 180, DEG = 180 / Math.PI;
|
|
15
|
+
|
|
16
|
+
// Longitude in [-180, 180), untouched when it's there already.
|
|
17
|
+
const wrap = (x) => (x >= -180 && x < 180 ? x : ((x + 180) % 360 + 360) % 360 - 180);
|
|
18
|
+
const isPole = (p) => p[1] >= 90 || p[1] <= -90;
|
|
19
|
+
|
|
20
|
+
// Every path of a geometry, as [positions, isRing], and its loose positions
|
|
21
|
+
// (Points and MultiPoints).
|
|
22
|
+
function parts(g, paths, points) {
|
|
23
|
+
const c = g.coordinates;
|
|
24
|
+
switch (g.type) {
|
|
25
|
+
case 'Point': if (c.length) points.push(c); break;
|
|
26
|
+
case 'MultiPoint': for (const p of c) points.push(p); break;
|
|
27
|
+
case 'LineString': paths.push([c, false]); break;
|
|
28
|
+
case 'MultiLineString': for (const l of c) paths.push([l, false]); break;
|
|
29
|
+
case 'Polygon': c.forEach((r, i) => paths.push([r, true, i === 0])); break;
|
|
30
|
+
case 'MultiPolygon': for (const poly of c) poly.forEach((r, i) => paths.push([r, true, i === 0])); break;
|
|
31
|
+
case 'GeometryCollection': for (const m of g.geometries) parts(m, paths, points); break;
|
|
32
|
+
default: throw new TypeError(`Unknown geometry type ${g.type}`);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// The edges of a path, as pairs of positions: a ring's closing edge
|
|
37
|
+
// included when it's open, and zero-length edges left out.
|
|
38
|
+
function edges(path, ring, fn) {
|
|
39
|
+
const len = path.length;
|
|
40
|
+
if (len < 2) return;
|
|
41
|
+
const last = ring && (path[len - 1][0] !== path[0][0] || path[len - 1][1] !== path[0][1]) ? len : len - 1;
|
|
42
|
+
for (let i = 1; i <= last; i++) {
|
|
43
|
+
const a = path[i - 1], b = path[i % len];
|
|
44
|
+
if (a[0] !== b[0] || a[1] !== b[1]) fn(a, b);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const unit = (p) => {
|
|
49
|
+
const l = p[0] * RAD, f = p[1] * RAD, cf = Math.cos(f);
|
|
50
|
+
return [cf * Math.cos(l), cf * Math.sin(l), Math.sin(f)];
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
// [lowest, highest] latitude the great-circle arc from a to b reaches
|
|
54
|
+
// strictly between its ends (null where it doesn't pass its ends' range).
|
|
55
|
+
function arcExtremes(p, q) {
|
|
56
|
+
const a = unit(p), b = unit(q);
|
|
57
|
+
const nx = a[1] * b[2] - a[2] * b[1], ny = a[2] * b[0] - a[0] * b[2], nz = a[0] * b[1] - a[1] * b[0];
|
|
58
|
+
const nn = Math.sqrt(nx * nx + ny * ny + nz * nz);
|
|
59
|
+
if (!(nn > 1e-15)) return null; // the same point, or antipodes (no single arc)
|
|
60
|
+
// m: the circle's northernmost point, z projected onto the circle's plane.
|
|
61
|
+
const k = nz / nn;
|
|
62
|
+
let mx = (-k * nx) / nn, my = (-k * ny) / nn, mz = 1 - k * k;
|
|
63
|
+
const ml = Math.sqrt(mx * mx + my * my + mz * mz);
|
|
64
|
+
if (!(ml > 1e-15)) return null; // the equator
|
|
65
|
+
mx /= ml; my /= ml; mz /= ml;
|
|
66
|
+
// m is on the arc when a, m, b turn the same way as a, b.
|
|
67
|
+
const turn = (u, x, y, z) => (u[1] * z - u[2] * y) * nx + (u[2] * x - u[0] * z) * ny + (u[0] * y - u[1] * x) * nz;
|
|
68
|
+
const turn2 = (x, y, z, v) => (y * v[2] - z * v[1]) * nx + (z * v[0] - x * v[2]) * ny + (x * v[1] - y * v[0]) * nz;
|
|
69
|
+
// The circle's top latitude: 90 degrees less the tilt of its axis, by
|
|
70
|
+
// atan2, which keeps its precision near the poles where asin(mz) doesn't.
|
|
71
|
+
const top = Math.atan2(Math.sqrt(nx * nx + ny * ny), Math.abs(nz)) * DEG;
|
|
72
|
+
const hi = turn(a, mx, my, mz) > 0 && turn2(mx, my, mz, b) > 0 ? top : null;
|
|
73
|
+
const lo = turn(a, -mx, -my, -mz) > 0 && turn2(-mx, -my, -mz, b) > 0 ? -top : null;
|
|
74
|
+
return hi === null && lo === null ? null : [lo, hi];
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* [west, south, east, north] of a geometry on the sphere, or null when it
|
|
79
|
+
* has no positions. west > east when the box crosses the antimeridian, and
|
|
80
|
+
* it's [-180, south, 180, north] when the geometry goes all the way round.
|
|
81
|
+
*/
|
|
82
|
+
export function bounds(g) {
|
|
83
|
+
const paths = [], points = [];
|
|
84
|
+
parts(g, paths, points);
|
|
85
|
+
let s = Infinity, n = -Infinity, lo = Infinity, hi = -Infinity, wide = false;
|
|
86
|
+
const see = (p) => {
|
|
87
|
+
const y = p[1];
|
|
88
|
+
if (y < s) s = y;
|
|
89
|
+
if (y > n) n = y;
|
|
90
|
+
if (isPole(p)) return;
|
|
91
|
+
if (p[0] < lo) lo = p[0];
|
|
92
|
+
if (p[0] > hi) hi = p[0];
|
|
93
|
+
};
|
|
94
|
+
for (const p of points) see(p);
|
|
95
|
+
let round = false;
|
|
96
|
+
for (const [path, ring, shell] of paths) {
|
|
97
|
+
let turn = 0, lat = 0;
|
|
98
|
+
for (const p of path) {
|
|
99
|
+
see(p);
|
|
100
|
+
lat += p[1];
|
|
101
|
+
}
|
|
102
|
+
edges(path, ring, (a, b) => {
|
|
103
|
+
if (!isPole(a) && !isPole(b)) {
|
|
104
|
+
if (Math.abs(b[0] - a[0]) > 180) wide = true;
|
|
105
|
+
const d = wrap(b[0] - a[0]);
|
|
106
|
+
if (d !== -180) turn += d;
|
|
107
|
+
}
|
|
108
|
+
const e = arcExtremes(a, b);
|
|
109
|
+
if (e) {
|
|
110
|
+
if (e[0] !== null && e[0] < s) s = e[0];
|
|
111
|
+
if (e[1] !== null && e[1] > n) n = e[1];
|
|
112
|
+
}
|
|
113
|
+
});
|
|
114
|
+
// A shell that goes once round the globe without passing a pole holds
|
|
115
|
+
// one: MongoDB takes the smaller side, so the pole on its side.
|
|
116
|
+
if (shell && Math.abs(turn) > 180) {
|
|
117
|
+
round = true;
|
|
118
|
+
if (lat >= 0) n = 90;
|
|
119
|
+
else s = -90;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
if (s === Infinity) return null;
|
|
123
|
+
if (s < -90) s = -90;
|
|
124
|
+
if (n > 90) n = 90;
|
|
125
|
+
if (lo === Infinity || round) return [-180, s, 180, n]; // only poles, or round one
|
|
126
|
+
if (!wide && hi - lo <= 180) return [lo, s, hi, n];
|
|
127
|
+
const [west, east] = circular(paths, points);
|
|
128
|
+
return [west, s, east, n];
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// The shortest arc of longitudes that holds every position and every edge,
|
|
132
|
+
// as [west, east]: the circle less its largest gap.
|
|
133
|
+
function circular(paths, points) {
|
|
134
|
+
const arcs = [];
|
|
135
|
+
// An arc as [from, to] within [-180, 180]; one that passes 180 is split in two.
|
|
136
|
+
const add = (a, d) => {
|
|
137
|
+
if (a + d <= 180) arcs.push([a, a + d]);
|
|
138
|
+
else { arcs.push([a, 180]); arcs.push([-180, a + d - 360]); }
|
|
139
|
+
};
|
|
140
|
+
for (const p of points) if (!isPole(p)) add(wrap(p[0]), 0);
|
|
141
|
+
for (const [path, ring] of paths) {
|
|
142
|
+
for (const p of path) if (!isPole(p)) add(wrap(p[0]), 0);
|
|
143
|
+
edges(path, ring, (a, b) => {
|
|
144
|
+
if (isPole(a) || isPole(b)) return;
|
|
145
|
+
const d = wrap(b[0] - a[0]);
|
|
146
|
+
if (d === -180) return; // through a pole: only its two meridians
|
|
147
|
+
if (d >= 0) add(wrap(a[0]), d);
|
|
148
|
+
else add(wrap(b[0]), -d);
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
arcs.sort((a, b) => a[0] - b[0]);
|
|
152
|
+
// The largest gap between merged runs, the one from the last run round to
|
|
153
|
+
// the first included, is what the box leaves out.
|
|
154
|
+
const first = arcs[0][0];
|
|
155
|
+
let end = arcs[0][1], gap = -1, west = 0, east = 0;
|
|
156
|
+
for (let i = 1; i < arcs.length; i++) {
|
|
157
|
+
const [a, b] = arcs[i];
|
|
158
|
+
if (a > end && a - end > gap) { gap = a - end; east = end; west = a; }
|
|
159
|
+
if (b > end) end = b;
|
|
160
|
+
}
|
|
161
|
+
if (first + 360 - end > gap) { gap = first + 360 - end; east = end; west = first; }
|
|
162
|
+
if (gap <= 0) return [-180, 180];
|
|
163
|
+
return [west === 180 ? -180 : west, east === -180 ? 180 : east];
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// The latitude to put a parallel edge of width d degrees at, so that read
|
|
167
|
+
// as a great-circle arc it doesn't pass `lat` toward the pole it bulges to:
|
|
168
|
+
// for the edge nearer the equator of a box in one hemisphere.
|
|
169
|
+
const parallel = (lat, d) => Math.atan(Math.tan(lat * RAD) * Math.cos((d / 2) * RAD)) * DEG;
|
|
170
|
+
|
|
171
|
+
// Width under which a box is widened, about a centimetre: S2, under
|
|
172
|
+
// MongoDB, refuses a ring with no area.
|
|
173
|
+
const THIN = 1e-7;
|
|
174
|
+
// A parallel edge is cut into steps of at most this many degrees, so that
|
|
175
|
+
// parallel() moves it by at most about a tenth of a degree.
|
|
176
|
+
const STEP = 10;
|
|
177
|
+
|
|
178
|
+
const norm = (x) => (x > 180 ? x - 360 : x);
|
|
179
|
+
|
|
180
|
+
// One ring over [w, w + d] x [s, n], 0 < d < 360, its parallel edges cut
|
|
181
|
+
// into steps of at most STEP degrees, counterclockwise.
|
|
182
|
+
function cell(w, d, s, n) {
|
|
183
|
+
const k = Math.max(1, Math.ceil(d / STEP)), e = w + d;
|
|
184
|
+
const south = s <= -90, north = n >= 90;
|
|
185
|
+
const sl = s > 0 ? parallel(s, d / k) : s, nl = n < 0 ? parallel(n, d / k) : n;
|
|
186
|
+
const x = (i) => norm(i === k ? e : w + (d * i) / k);
|
|
187
|
+
const ring = [];
|
|
188
|
+
// A meridian edge longer than 90 degrees gets a midpoint, so that no edge
|
|
189
|
+
// comes near half a great circle.
|
|
190
|
+
const side = (lon, from, to) => { if (Math.abs(to - from) > 90) ring.push([norm(lon), (from + to) / 2]); };
|
|
191
|
+
if (south) ring.push([norm(w), -90]);
|
|
192
|
+
else for (let i = 0; i <= k; i++) ring.push([x(i), sl]);
|
|
193
|
+
side(e, south ? -90 : sl, north ? 90 : nl);
|
|
194
|
+
if (north) ring.push([norm(e), 90]);
|
|
195
|
+
else for (let i = k; i >= 0; i--) ring.push([x(i), nl]);
|
|
196
|
+
side(w, north ? 90 : nl, south ? -90 : sl);
|
|
197
|
+
ring.push(ring[0].slice());
|
|
198
|
+
return ring;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* A GeoJSON geometry that covers the box [west, south, east, north] on the
|
|
203
|
+
* sphere and that MongoDB's 2dsphere index takes: a Point for a point, a
|
|
204
|
+
* Polygon for most boxes, and a MultiPolygon of slices for a box that's
|
|
205
|
+
* near half the sphere or more.
|
|
206
|
+
*/
|
|
207
|
+
export function cover(box) {
|
|
208
|
+
let [w, s, e, n] = box;
|
|
209
|
+
let d = w === -180 && e === 180 ? 360 : e >= w ? e - w : e - w + 360;
|
|
210
|
+
if (s === n && (d === 0 || s === 90 || s === -90)) return { type: 'Point', coordinates: [d === 0 ? w : 0, s] };
|
|
211
|
+
if (d < THIN) { w -= (THIN - d) / 2; d = THIN; }
|
|
212
|
+
if (n - s < THIN) {
|
|
213
|
+
const m = (s + n) / 2;
|
|
214
|
+
s = Math.max(-90, m - THIN / 2);
|
|
215
|
+
n = Math.min(90, m + THIN / 2);
|
|
216
|
+
}
|
|
217
|
+
w = wrap(w);
|
|
218
|
+
const south = s <= -90, north = n >= 90;
|
|
219
|
+
// All the way round one pole and not too far from it: one ring along a
|
|
220
|
+
// parallel. West round the south pole and east round the north one, so
|
|
221
|
+
// the cap is on the left, as RFC 7946 has it.
|
|
222
|
+
if (d === 360 && south !== north && (south ? n < -30 : s > 30)) {
|
|
223
|
+
const k = Math.ceil(360 / STEP), lat = parallel(south ? n : s, 360 / k), ring = [];
|
|
224
|
+
for (let i = 0; i < k; i++) ring.push([wrap(south ? 180 - (360 * i) / k : -180 + (360 * i) / k), lat]);
|
|
225
|
+
ring.push(ring[0].slice());
|
|
226
|
+
return { type: 'Polygon', coordinates: [ring] };
|
|
227
|
+
}
|
|
228
|
+
// MongoDB reads a ring as the smaller of the two areas it bounds, so a
|
|
229
|
+
// box near half the sphere or more is cut into slices of at most 90 degrees.
|
|
230
|
+
const area = ((Math.sin(n * RAD) - Math.sin(s * RAD)) / 2) * (d / 360);
|
|
231
|
+
if (d < 360 && area < 0.4) return { type: 'Polygon', coordinates: [cell(w, d, s, n)] };
|
|
232
|
+
const k = Math.ceil(d / 90), polys = [];
|
|
233
|
+
for (let i = 0; i < k; i++) polys.push([cell(w + (d * i) / k, d / k, s, n)]);
|
|
234
|
+
return { type: 'MultiPolygon', coordinates: polys };
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* A representative point of a geometry, [lng, lat], or null when it has no
|
|
239
|
+
* positions: the planar centroid of its polygons by area, or else of its
|
|
240
|
+
* lines by length, or else the mean of its positions, the way Shapely and
|
|
241
|
+
* Turf's centerOfMass take it, with longitudes unwrapped across the
|
|
242
|
+
* antimeridian. It can lie outside a concave polygon, never outside the
|
|
243
|
+
* geometry's box: where a ring that crosses itself would put it there, it's
|
|
244
|
+
* the middle of the box.
|
|
245
|
+
*/
|
|
246
|
+
export function centroid(g) {
|
|
247
|
+
const b = bounds(g);
|
|
248
|
+
if (!b) return null;
|
|
249
|
+
const w = b[0], cross = b[0] > b[2];
|
|
250
|
+
const X = (x) => (cross && x < w ? x + 360 : x);
|
|
251
|
+
const paths = [], points = [], polys = [];
|
|
252
|
+
parts(g, paths, points);
|
|
253
|
+
const collect = (m) => {
|
|
254
|
+
if (m.type === 'Polygon') polys.push(m.coordinates);
|
|
255
|
+
else if (m.type === 'MultiPolygon') for (const p of m.coordinates) polys.push(p);
|
|
256
|
+
else if (m.type === 'GeometryCollection') m.geometries.forEach(collect);
|
|
257
|
+
};
|
|
258
|
+
collect(g);
|
|
259
|
+
// Polygons: area times centroid summed over rings, a shell's counted up
|
|
260
|
+
// and its holes' down, whichever way they wind.
|
|
261
|
+
let A = 0, ax = 0, ay = 0;
|
|
262
|
+
for (const rings of polys) {
|
|
263
|
+
rings.forEach((r, j) => {
|
|
264
|
+
if (r.length < 3) return;
|
|
265
|
+
const x0 = X(r[0][0]), y0 = r[0][1];
|
|
266
|
+
let a = 0, cx = 0, cy = 0;
|
|
267
|
+
for (let i = 1; i + 1 < r.length; i++) {
|
|
268
|
+
const x1 = X(r[i][0]) - x0, y1 = r[i][1] - y0, x2 = X(r[i + 1][0]) - x0, y2 = r[i + 1][1] - y0;
|
|
269
|
+
const t = x1 * y2 - x2 * y1;
|
|
270
|
+
a += t;
|
|
271
|
+
cx += t * (x1 + x2);
|
|
272
|
+
cy += t * (y1 + y2);
|
|
273
|
+
}
|
|
274
|
+
if (a === 0) return;
|
|
275
|
+
const area = (j === 0 ? 1 : -1) * Math.abs(a) / 2;
|
|
276
|
+
A += area;
|
|
277
|
+
ax += area * (x0 + cx / (3 * a));
|
|
278
|
+
ay += area * (y0 + cy / (3 * a));
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
let x, y;
|
|
282
|
+
if (A > 0) {
|
|
283
|
+
x = ax / A;
|
|
284
|
+
y = ay / A;
|
|
285
|
+
} else {
|
|
286
|
+
let L = 0, lx = 0, ly = 0;
|
|
287
|
+
for (const [path, ring] of paths) {
|
|
288
|
+
edges(path, ring, (a, c) => {
|
|
289
|
+
const xa = X(a[0]), xc = X(c[0]), l = Math.sqrt((xc - xa) * (xc - xa) + (c[1] - a[1]) * (c[1] - a[1]));
|
|
290
|
+
L += l;
|
|
291
|
+
lx += (l * (xa + xc)) / 2;
|
|
292
|
+
ly += (l * (a[1] + c[1])) / 2;
|
|
293
|
+
});
|
|
294
|
+
}
|
|
295
|
+
if (L > 0) {
|
|
296
|
+
x = lx / L;
|
|
297
|
+
y = ly / L;
|
|
298
|
+
} else {
|
|
299
|
+
let P = 0, px = 0, py = 0;
|
|
300
|
+
const add = (p) => { P++; px += X(p[0]); py += p[1]; };
|
|
301
|
+
points.forEach(add);
|
|
302
|
+
for (const [path] of paths) path.forEach(add);
|
|
303
|
+
x = px / P;
|
|
304
|
+
y = py / P;
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
// A ring that crosses itself can cancel its own area and put the
|
|
308
|
+
// centroid anywhere: then the middle of the box.
|
|
309
|
+
const span = cross ? b[2] + 360 - w : b[2] - w;
|
|
310
|
+
if (!(x >= w - 1e-9 && x <= w + span + 1e-9 && y >= b[1] - 1e-9 && y <= b[3] + 1e-9)) {
|
|
311
|
+
x = w + span / 2;
|
|
312
|
+
y = (b[1] + b[3]) / 2;
|
|
313
|
+
}
|
|
314
|
+
return [x > 180 ? x - 360 : x, y];
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** Throws a RangeError for a position that isn't a longitude and a latitude, which `what` needs. */
|
|
318
|
+
export function onGlobe(g, what) {
|
|
319
|
+
const walk = (c) => {
|
|
320
|
+
if (typeof c[0] === 'number') {
|
|
321
|
+
if (!(c[0] >= -180 && c[0] <= 180 && c[1] >= -90 && c[1] <= 90)) throw new RangeError(`[${c[0]}, ${c[1]}] isn't a longitude and latitude, which ${what} needs`);
|
|
322
|
+
} else for (const x of c) walk(x);
|
|
323
|
+
};
|
|
324
|
+
const geom = (m) => (m.type === 'GeometryCollection' ? m.geometries.forEach(geom) : walk(m.coordinates));
|
|
325
|
+
geom(g);
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/**
|
|
329
|
+
* The geometry as MongoDB's 2dsphere index takes it, or null when it has no
|
|
330
|
+
* positions: 2D positions, open rings closed, a position repeated in a row
|
|
331
|
+
* left out, a line of one position as a Point, and empty parts dropped.
|
|
332
|
+
* Whatever else MongoDB refuses (a ring that crosses itself, a hole outside
|
|
333
|
+
* its shell) stays as it is.
|
|
334
|
+
*/
|
|
335
|
+
export function sphereGeometry(g) {
|
|
336
|
+
const pos = (p) => [p[0], p[1]];
|
|
337
|
+
const path = (c, ring) => {
|
|
338
|
+
const out = [];
|
|
339
|
+
for (const p of c) {
|
|
340
|
+
const q = out[out.length - 1];
|
|
341
|
+
if (!q || q[0] !== p[0] || q[1] !== p[1]) out.push(pos(p));
|
|
342
|
+
}
|
|
343
|
+
if (ring && out.length && (out[0][0] !== out[out.length - 1][0] || out[0][1] !== out[out.length - 1][1])) out.push(out[0].slice());
|
|
344
|
+
return out;
|
|
345
|
+
};
|
|
346
|
+
const poly = (rings) => rings.map((r) => path(r, true)).filter((r) => r.length);
|
|
347
|
+
const c = g.coordinates;
|
|
348
|
+
switch (g.type) {
|
|
349
|
+
case 'Point': return c.length ? { type: 'Point', coordinates: pos(c) } : null;
|
|
350
|
+
case 'MultiPoint': return c.length ? { type: 'MultiPoint', coordinates: c.map(pos) } : null;
|
|
351
|
+
case 'LineString': {
|
|
352
|
+
const l = path(c, false);
|
|
353
|
+
return !l.length ? null : l.length === 1 ? { type: 'Point', coordinates: l[0] } : { type: 'LineString', coordinates: l };
|
|
354
|
+
}
|
|
355
|
+
case 'MultiLineString': {
|
|
356
|
+
const ls = c.map((l) => path(l, false)).filter((l) => l.length > 1);
|
|
357
|
+
return ls.length ? { type: 'MultiLineString', coordinates: ls } : null;
|
|
358
|
+
}
|
|
359
|
+
case 'Polygon': {
|
|
360
|
+
const p = poly(c);
|
|
361
|
+
return p.length ? { type: 'Polygon', coordinates: p } : null;
|
|
362
|
+
}
|
|
363
|
+
case 'MultiPolygon': {
|
|
364
|
+
const ps = c.map(poly).filter((p) => p.length);
|
|
365
|
+
return ps.length ? { type: 'MultiPolygon', coordinates: ps } : null;
|
|
366
|
+
}
|
|
367
|
+
case 'GeometryCollection': {
|
|
368
|
+
const gs = g.geometries.map(sphereGeometry).filter(Boolean);
|
|
369
|
+
return gs.length ? { type: 'GeometryCollection', geometries: gs } : null;
|
|
370
|
+
}
|
|
371
|
+
default: throw new TypeError(`Unknown geometry type ${g.type}`);
|
|
372
|
+
}
|
|
373
|
+
}
|