@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/src/google.js ADDED
@@ -0,0 +1,113 @@
1
+ // Google Maps JavaScript API: geotini strings to paths for google.maps
2
+ // Polyline and Polygon, to features of a google.maps.Data layer, and back.
3
+ //
4
+ // import { toPaths, encodePolygon, addGeoJson } from '@duoquote/geotini/google';
5
+ // new google.maps.Polygon({ paths: toPaths(str), map });
6
+ // const str = encodePolygon(polygon.getPaths(), 6);
7
+ // addGeoJson(map.data, strings); // any geometry type, through the Data layer
8
+ //
9
+ // The Maps API isn't loaded or imported. Paths come out as LatLngLiteral
10
+ // objects ({ lat, lng }), which Polyline, Polygon and most Maps API methods
11
+ // take, or as google.maps.LatLng objects with `{ LatLng }` in the options.
12
+ // The encoders take arrays or MVCArrays of LatLng objects, literals or
13
+ // [lat, lng] tuples.
14
+ //
15
+ // Google's polygon paths don't repeat the first point at the end, and
16
+ // GeoJSON rings do: toPaths drops the closing point, and encodePolygon adds
17
+ // it back.
18
+ /* @ts-self-types="../types/google.d.ts" */
19
+ import { encode, decode, encodeLine, GeotiniError } from './geotini.js';
20
+ import { toFeatureCollection } from './turf.js';
21
+
22
+ const point = (C) => (C ? (p) => new C(p[1], p[0]) : (p) => ({ lat: p[1], lng: p[0] }));
23
+ const open = (ring) => (ring.length > 1 && ring[0][0] === ring[ring.length - 1][0] && ring[0][1] === ring[ring.length - 1][1] ? ring.slice(0, -1) : ring);
24
+
25
+ /**
26
+ * The paths of a line or polygon string, ready for google.maps.Polyline
27
+ * (`path`) or google.maps.Polygon (`paths`):
28
+ * - LineString: one path.
29
+ * - MultiLineString: one path per line.
30
+ * - Polygon: one path per ring, the outer ring first, without the closing point.
31
+ * Use toPolygons for a MultiPolygon. Options: `LatLng`, a constructor, for
32
+ * LatLng objects instead of literals, and decode's `checksum`, `maxLength`
33
+ * and `maxPositions`. toPolygons, decodePath and addGeoJson take them too.
34
+ */
35
+ export function toPaths(str, options) {
36
+ const g = decode(str, options), p = point(options?.LatLng);
37
+ if (g.type == 'LineString') return [g.coordinates.map(p)];
38
+ if (g.type == 'MultiLineString') return g.coordinates.map((l) => l.map(p));
39
+ if (g.type == 'Polygon') return g.coordinates.map((r) => open(r).map(p));
40
+ throw new GeotiniError('WRONG_TYPE', `Expected a LineString, MultiLineString or Polygon, got a ${g.type}${g.type == 'MultiPolygon' ? '; use toPolygons' : ''}`);
41
+ }
42
+
43
+ /** The path of a LineString string, like google.maps.geometry.encoding.decodePath. */
44
+ export const decodePath = (str, options) => {
45
+ const g = decode(str, options);
46
+ if (g.type != 'LineString') throw new GeotiniError('WRONG_TYPE', `Expected a LineString, got a ${g.type}`);
47
+ return g.coordinates.map(point(options?.LatLng));
48
+ };
49
+
50
+ /** One `paths` array per polygon of a Polygon or MultiPolygon string, for a google.maps.Polygon each. */
51
+ export function toPolygons(str, options) {
52
+ const g = decode(str, options), p = point(options?.LatLng);
53
+ const paths = (rings) => rings.map((r) => open(r).map(p));
54
+ if (g.type == 'Polygon') return [paths(g.coordinates)];
55
+ if (g.type == 'MultiPolygon') return g.coordinates.map(paths);
56
+ throw new GeotiniError('WRONG_TYPE', `Expected a Polygon or MultiPolygon, got a ${g.type}`);
57
+ }
58
+
59
+ // [lat, lng] from a LatLng object, a literal or a tuple; an MVCArray to an array.
60
+ const array = (a) => (a && typeof a.getArray == 'function' ? a.getArray() : a);
61
+ const latLng = (p) => (typeof p?.lat == 'function' ? [p.lat(), p.lng()] : Array.isArray(p) ? p : [p?.lat, p?.lng]);
62
+
63
+ /** Encodes a path (array or MVCArray of LatLng, LatLngLiteral or [lat, lng]) as a LineString, like google.maps.geometry.encoding.encodePath. */
64
+ export function encodePath(path, options) {
65
+ const a = array(path);
66
+ if (!Array.isArray(a)) throw new TypeError('Expected an array or MVCArray of points');
67
+ return encodeLine(a.map(latLng), options);
68
+ }
69
+
70
+ /**
71
+ * Encodes a polygon's paths (from Polygon.getPaths(), or arrays of points)
72
+ * as a Polygon: the first path is the outer ring, the others are holes.
73
+ * Each ring is closed for GeoJSON: the first point is added at the end,
74
+ * unless the path already ends with it.
75
+ */
76
+ export function encodePolygon(paths, options) {
77
+ const rings = array(paths);
78
+ if (!Array.isArray(rings)) throw new TypeError('Expected an array or MVCArray of paths');
79
+ const coordinates = rings.map((r) => {
80
+ const ring = array(r).map((p) => {
81
+ const [lat, lng] = latLng(p);
82
+ return [lng, lat];
83
+ });
84
+ if (ring.length && (ring[0][0] !== ring[ring.length - 1][0] || ring[0][1] !== ring[ring.length - 1][1])) ring.push(ring[0].slice());
85
+ return ring;
86
+ });
87
+ return encode({ type: 'Polygon', coordinates }, options);
88
+ }
89
+
90
+ /**
91
+ * Adds one Feature per string to a google.maps.Data layer (map.data, or a
92
+ * new google.maps.Data), any geometry type, and returns the Data.Features
93
+ * it made. Options: `properties` and `id` for the Features, `idPropertyName`
94
+ * for Data.addGeoJson, and decode's.
95
+ */
96
+ export function addGeoJson(data, encoded, options) {
97
+ const opts = options?.idPropertyName ? { idPropertyName: options.idPropertyName } : undefined;
98
+ return data.addGeoJson(toFeatureCollection(encoded, options), opts);
99
+ }
100
+
101
+ /** Encodes every feature of a google.maps.Data layer, one string per feature, through Data.toGeoJson. */
102
+ export function encodeData(data, options) {
103
+ return new Promise((resolve, reject) => {
104
+ data.toGeoJson((fc) => {
105
+ try {
106
+ resolve(fc.features.filter((f) => f.geometry).map((f) => encode(f.geometry, options)));
107
+ } catch (e) {
108
+ reject(e);
109
+ }
110
+ });
111
+ });
112
+ }
113
+
package/src/leaflet.js ADDED
@@ -0,0 +1,82 @@
1
+ // Leaflet: geotini strings to layers, and layers back to strings.
2
+ //
3
+ // import L from 'leaflet';
4
+ // import { install } from '@duoquote/geotini/leaflet';
5
+ // install(L);
6
+ // L.GeoJSON.fromGeotini(str).addTo(map); // any geometry type
7
+ // L.Polygon.fromGeotini(str, { color: 'red' }).addTo(map);
8
+ // const str = layer.toGeotini(6); // any layer with toGeoJSON
9
+ //
10
+ // Works with Leaflet 1.9 and the Leaflet 2 betas. In Leaflet 2, L is a
11
+ // frozen module namespace of ES classes: the static and prototype methods
12
+ // are added, and the lower-case factory L.geotini is skipped because the
13
+ // namespace can't take new properties. Leaflet isn't imported; install()
14
+ // and the functions take it from you.
15
+ /* @ts-self-types="../types/leaflet.d.ts" */
16
+ import { encode, decode, GeotiniError } from './geotini.js';
17
+ import { toFeatureCollection } from './turf.js';
18
+
19
+ // GeoJSON [lng, lat, z] to Leaflet's [lat, lng, alt]. An M value has no
20
+ // place in a LatLng and is left out.
21
+ const ll = (p) => (p.length > 2 ? [p[1], p[0], p[2]] : [p[1], p[0]]);
22
+ const LINES = { LineString: 0, MultiLineString: 1 }, POLYS = { Polygon: 1, MultiPolygon: 2 };
23
+
24
+ /**
25
+ * Leaflet's latlngs for a line or polygon string: LatLng arrays, nested the
26
+ * way L.Polyline (LineString, MultiLineString) and L.Polygon (Polygon with
27
+ * holes, MultiPolygon) take them. Options are decode's.
28
+ */
29
+ export const toLatLngs = (str, options) => latLngs(decode(str, options), { ...LINES, ...POLYS }, 'a line or polygon');
30
+
31
+ function latLngs(g, kinds, what) {
32
+ const depth = kinds[g.type];
33
+ if (depth === undefined) throw new GeotiniError('WRONG_TYPE', `Expected ${what}, got a ${g.type}`);
34
+ const walk = (c, d) => (d === 0 ? c.map(ll) : c.map((x) => walk(x, d - 1)));
35
+ return walk(g.coordinates, depth);
36
+ }
37
+
38
+ /**
39
+ * An L.GeoJSON layer for one string or many, any geometry type. `options`
40
+ * are L.GeoJSON's, plus `properties` and `id` for the Features and decode's
41
+ * `checksum`, `maxLength` and `maxPositions`.
42
+ */
43
+ export function toLayer(L, encoded, options) {
44
+ const data = typeof encoded == 'string' ? decode(encoded, options) : toFeatureCollection(encoded, options);
45
+ return new L.GeoJSON(data, options);
46
+ }
47
+
48
+ /**
49
+ * Encodes a layer through its toGeoJSON(): a Marker, CircleMarker,
50
+ * Polyline, Polygon, or a group such as L.GeoJSON or L.FeatureGroup. A group
51
+ * of more than one geometry becomes one GeometryCollection string.
52
+ * Coordinates are taken at full precision (toGeoJSON(false)), then rounded
53
+ * to `options`' precision.
54
+ */
55
+ export function fromLayer(layer, options) {
56
+ if (typeof layer?.toGeoJSON != 'function') throw new TypeError('Expected a Leaflet layer with toGeoJSON()');
57
+ const g = layer.toGeoJSON(false);
58
+ if (g.type == 'FeatureCollection') {
59
+ const geometries = g.features.map((f) => f.geometry).filter(Boolean);
60
+ return encode(geometries.length == 1 ? geometries[0] : { type: 'GeometryCollection', geometries }, options);
61
+ }
62
+ return encode(g.type == 'Feature' ? g.geometry : g, options);
63
+ }
64
+
65
+ /**
66
+ * Adds L.Polyline.fromGeotini, L.Polygon.fromGeotini, L.GeoJSON.fromGeotini
67
+ * and layer.toGeotini() to the Leaflet you pass, and the factory L.geotini
68
+ * where L can take new properties (Leaflet 1.9). Returns L. The layer
69
+ * options of each fromGeotini also take decode's `checksum`, `maxLength` and
70
+ * `maxPositions`; Leaflet keeps them in layer.options and doesn't use them.
71
+ */
72
+ export function install(L) {
73
+ L.Polyline.fromGeotini = (s, o) => new L.Polyline(latLngs(decode(s, o), LINES, 'a LineString or MultiLineString'), o);
74
+ L.Polygon.fromGeotini = (s, o) => new L.Polygon(latLngs(decode(s, o), POLYS, 'a Polygon or MultiPolygon'), o);
75
+ L.GeoJSON.fromGeotini = (s, o) => toLayer(L, s, o);
76
+ L.Layer.prototype.toGeotini = function (o) {
77
+ return fromLayer(this, o);
78
+ };
79
+ if (Object.isExtensible(L)) L.geotini = L.GeoJSON.fromGeotini;
80
+ return L;
81
+ }
82
+
package/src/mapbox.js ADDED
@@ -0,0 +1,8 @@
1
+ // Mapbox GL JS 3: the same functions as the MapLibre module. addSource with
2
+ // a GeoJSON source, addLayer with a beforeId and getSource(id).setData take
3
+ // the same arguments in both libraries.
4
+ //
5
+ // import { addGeotiniLayer } from '@duoquote/geotini/mapbox';
6
+ // map.on('load', () => addGeotiniLayer(map, 'route', str, { layer: { paint: { 'line-color': '#c00' } } }));
7
+ /* @ts-self-types="../types/mapbox.d.ts" */
8
+ export { geotiniData, geotiniSource, addGeotiniLayer, setGeotiniData, fromFeature, fromFeatureCollection } from './maplibre.js';
@@ -0,0 +1,74 @@
1
+ // MapLibre GL JS (and Mapbox GL JS, see mapbox.js): geotini strings as
2
+ // GeoJSON sources and layers.
3
+ //
4
+ // import { addGeotiniLayer, setGeotiniData } from '@duoquote/geotini/maplibre';
5
+ // map.on('load', () => addGeotiniLayer(map, 'parcels', strings, { layer: { paint: { 'fill-color': '#0a7' } } }));
6
+ // setGeotiniData(map, 'parcels', newStrings);
7
+ //
8
+ // No map library code is imported: the functions only call addSource,
9
+ // addLayer and getSource(id).setData on the map they're given, which
10
+ // MapLibre GL 4 to 6 and Mapbox GL 3 all have with the same arguments.
11
+ /* @ts-self-types="../types/maplibre.d.ts" */
12
+ import { toFeatureCollection } from './turf.js';
13
+
14
+ /**
15
+ * The FeatureCollection for one string or many, any geometry type. Options:
16
+ * `properties` and `id` (one value for every Feature, or an array with one
17
+ * per string), `bbox`, and decode's `checksum`, `maxLength` and
18
+ * `maxPositions`, which hold for each string. Every function here that
19
+ * takes strings takes these options too.
20
+ */
21
+ export const geotiniData = (encoded, options) => toFeatureCollection(encoded, options);
22
+
23
+ /** A GeoJSON source specification, `{ type: 'geojson', data }`. `options.source` adds source options such as promoteId or tolerance. */
24
+ export const geotiniSource = (encoded, options) => ({ ...options?.source, type: 'geojson', data: geotiniData(encoded, options) });
25
+
26
+ // The layer type that draws a geometry: fill for polygons, line for lines,
27
+ // circle for points. The first non-empty geometry decides.
28
+ const KIND = { Polygon: 'fill', MultiPolygon: 'fill', LineString: 'line', MultiLineString: 'line', Point: 'circle', MultiPoint: 'circle' };
29
+ function kindOf(g) {
30
+ if (g.type == 'GeometryCollection') {
31
+ for (const m of g.geometries) {
32
+ const k = kindOf(m);
33
+ if (k) return k;
34
+ }
35
+ return null;
36
+ }
37
+ return g.coordinates.length ? KIND[g.type] : null;
38
+ }
39
+
40
+ /**
41
+ * Adds a GeoJSON source and one layer that draws it, both named `id`. The
42
+ * layer type follows the geometry: `fill` for polygons, `line` for lines,
43
+ * `circle` for points (from the first non-empty geometry), unless
44
+ * `options.layer.type` says otherwise. `options.layer` is merged into the
45
+ * layer and `options.beforeId` is passed to addLayer. For strings of mixed
46
+ * types, add more layers on the same source with a `['geometry-type']`
47
+ * filter. Returns the map.
48
+ */
49
+ export function addGeotiniLayer(map, id, encoded, options) {
50
+ const source = geotiniSource(encoded, options);
51
+ let type = 'line';
52
+ for (const f of source.data.features) {
53
+ const k = kindOf(f.geometry);
54
+ if (k) {
55
+ type = k;
56
+ break;
57
+ }
58
+ }
59
+ map.addSource(id, source);
60
+ map.addLayer({ id, type, source: id, ...options?.layer }, options?.beforeId);
61
+ return map;
62
+ }
63
+
64
+ /**
65
+ * Replaces the data of the GeoJSON source `id` and returns what its setData
66
+ * returns. Throws a TypeError if there's no such GeoJSON source.
67
+ */
68
+ export function setGeotiniData(map, id, encoded, options) {
69
+ const source = map.getSource(id);
70
+ if (typeof source?.setData != 'function') throw new TypeError('No GeoJSON source named ' + id);
71
+ return source.setData(geotiniData(encoded, options));
72
+ }
73
+
74
+ export { fromFeature, fromFeatureCollection } from './turf.js';
package/src/mongodb.js ADDED
@@ -0,0 +1,179 @@
1
+ // Geometries in MongoDB as geotini strings. MongoDB's 2dsphere index only
2
+ // reads GeoJSON, so a document keeps the string, which holds the geometry
3
+ // exactly, next to a small GeoJSON geometry for the index: the geometry's
4
+ // box as a polygon, its centroid, or the whole geometry when queries must
5
+ // be exact. No MongoDB code is imported: these functions build documents,
6
+ // index specifications and query filters as plain objects for any driver.
7
+ //
8
+ // import { toDocument, fromDocument, indexSpec, geoIntersects } from '@duoquote/geotini/mongodb';
9
+ // await parcels.createIndex(indexSpec()); // { geom_index: '2dsphere' }
10
+ // await parcels.insertOne({ name, ...toDocument(geometry, { precision: 6 }) });
11
+ // for await (const doc of parcels.find(geoIntersects(viewport))) draw(fromDocument(doc));
12
+ //
13
+ // With `binary: true` the field holds the geometry's binary value (SPEC.md
14
+ // section 23) instead of its string: a Uint8Array, which the driver stores
15
+ // as BSON Binary, about three quarters of the string's bytes.
16
+ /* @ts-self-types="../types/mongodb.d.ts" */
17
+ import { encode, decode, canonical, encodeValue, decodeValue, canonicalValue, toValue, fromValue } from './geotini.js';
18
+ import { bounds, cover, centroid, sphereGeometry, onGlobe as check } from './geoindex.js';
19
+
20
+ const onGlobe = (g) => check(g, "MongoDB's 2dsphere index");
21
+
22
+ const STRICT = { type: 'name', properties: { name: 'urn:x-mongodb:crs:strictwinding:EPSG:4326' } };
23
+ const MODES = ['bbox', 'centroid', 'geometry'];
24
+ // Our own strings, read back to build the index: no limits.
25
+ const OWN = { maxLength: Infinity, maxPositions: Infinity };
26
+
27
+ const fields = (o) => {
28
+ const field = o?.field ?? 'geom';
29
+ if (typeof field !== 'string' || !field) throw new TypeError('field must be a non-empty string');
30
+ const index = o?.indexField ?? `${field}_index`;
31
+ if (typeof index !== 'string' || !index || index === field) throw new TypeError('indexField must be a non-empty string other than field');
32
+ return [field, index];
33
+ };
34
+
35
+ // The options of decode, from an object that may hold others.
36
+ const reading = (o) => (o == null ? undefined : { checksum: o.checksum, maxLength: o.maxLength, maxPositions: o.maxPositions });
37
+
38
+ // A binary value as the driver gives it back: a Uint8Array (a Buffer with
39
+ // promoteBuffers), or a BSON Binary of the generic subtype, whose buffer
40
+ // can be longer than its content. null for anything else.
41
+ const bytesOf = (v) => {
42
+ if (v instanceof Uint8Array) return v;
43
+ if (v?._bsontype === 'Binary' && v.buffer instanceof Uint8Array && (v.sub_type ?? 0) === 0) return v.buffer.subarray(0, v.position ?? v.buffer.length);
44
+ return null;
45
+ };
46
+
47
+ // What a geometry input decodes to: a geotini string, a binary value, or a
48
+ // geometry or Feature as it is.
49
+ const geometryOf = (input, read) => {
50
+ if (typeof input === 'string') return decode(input, read);
51
+ const b = bytesOf(input);
52
+ return b ? decodeValue(b, read) : input;
53
+ };
54
+
55
+ const target = (o) => {
56
+ if (o?.favor !== undefined) throw new RangeError("the strings are always written with favor 'size', the canonical encoder");
57
+ return { precision: o?.precision, zPrecision: o?.zPrecision, mPrecision: o?.mPrecision, checksum: o?.checksum };
58
+ };
59
+
60
+ /**
61
+ * The canonical string for a geometry, a Feature, a geotini string or a
62
+ * binary value, at the settings in options (encode's, defaults included):
63
+ * what toDocument writes, and so the value to look a geometry up by, or to
64
+ * keep unique. With `binary: true` it's the canonical binary value, a
65
+ * Uint8Array. A string or a value is read with options.decode, decode's
66
+ * options, and written again at the settings, so its own precision doesn't
67
+ * carry over.
68
+ */
69
+ export function key(input, options) {
70
+ const to = target(options), read = reading(options?.decode), binary = options?.binary === true;
71
+ if (options?.binary !== undefined && typeof options.binary !== 'boolean') throw new TypeError('binary must be true or false');
72
+ if (typeof input === 'string') return binary ? toValue(canonical(input, { ...read, to }), OWN) : canonical(input, { ...read, to });
73
+ const b = bytesOf(input);
74
+ if (b) return binary ? canonicalValue(b, { ...read, to }) : canonical(fromValue(b, read), { ...OWN, to });
75
+ return binary ? encodeValue(input, { ...to, favor: 'size' }) : encode(input, { ...to, favor: 'size' });
76
+ }
77
+
78
+ /**
79
+ * The GeoJSON geometry the index field gets for a geometry, or null when it
80
+ * has no positions. 'bbox' covers its box on the sphere, 'centroid' is a
81
+ * Point, and 'geometry' is the geometry itself in 2D with its rings closed.
82
+ * Throws a RangeError for a position that isn't a longitude and latitude.
83
+ */
84
+ export function indexGeometry(geometry, index = 'bbox') {
85
+ if (!MODES.includes(index)) throw new RangeError(`index must be one of ${MODES.join(', ')}, or false`);
86
+ if (geometry?.type === 'Feature') geometry = geometry.geometry;
87
+ onGlobe(geometry);
88
+ if (index === 'geometry') return sphereGeometry(geometry);
89
+ if (index === 'centroid') {
90
+ const c = centroid(geometry);
91
+ return c && { type: 'Point', coordinates: c };
92
+ }
93
+ const b = bounds(geometry);
94
+ return b && cover(b);
95
+ }
96
+
97
+ /**
98
+ * The fields to put in a document: the canonical geotini string at
99
+ * options.field ('geom'), or its binary value with `binary: true`, and the
100
+ * index geometry at options.indexField (field + '_index'), null when
101
+ * there's nothing to index. options.index is 'bbox' (the default),
102
+ * 'centroid', 'geometry', or false for no index field. The other options
103
+ * are encode's, and options.decode reads a string or a value.
104
+ */
105
+ export function toDocument(input, options) {
106
+ const [field, indexField] = fields(options);
107
+ const index = options?.index ?? 'bbox';
108
+ if (index !== false && !MODES.includes(index)) throw new RangeError(`index must be one of ${MODES.join(', ')}, or false`);
109
+ const s = key(input, options);
110
+ const out = { [field]: s };
111
+ if (index !== false) out[indexField] = indexGeometry(typeof s === 'string' ? decode(s, OWN) : decodeValue(s, OWN), index);
112
+ return out;
113
+ }
114
+
115
+ /**
116
+ * The geometry of a document, decoded from options.field ('geom', a dotted
117
+ * path works), or null when the document has none. A string field is
118
+ * decoded as a string, and a binary one (a BSON Binary, a Buffer or a
119
+ * Uint8Array) as a binary value: BSON says which it is. The other options
120
+ * are decode's: set them for documents others can write.
121
+ */
122
+ export function fromDocument(doc, options) {
123
+ const [field] = fields(options);
124
+ let v = doc;
125
+ for (const part of field.split('.')) v = v?.[part];
126
+ if (v == null) return null;
127
+ const b = bytesOf(v);
128
+ return b ? decodeValue(b, reading(options)) : decode(v, reading(options));
129
+ }
130
+
131
+ /** The 2dsphere index on the index field, for createIndex: `{ geom_index: '2dsphere' }`. */
132
+ export function indexSpec(options) {
133
+ return { [fields(options)[1]]: '2dsphere' };
134
+ }
135
+
136
+ function area(input, options) {
137
+ let g = geometryOf(input, reading(options?.decode));
138
+ if (g?.type === 'Feature') g = g.geometry;
139
+ if (g == null || typeof g.type !== 'string') throw new TypeError('Expected a geometry, a Feature, a geotini string or a binary value');
140
+ onGlobe(g);
141
+ const out = sphereGeometry(g);
142
+ if (!out) throw new RangeError('The query geometry is empty');
143
+ if (options?.strict) {
144
+ if (out.type !== 'Polygon') throw new RangeError('strict works on a Polygon only');
145
+ out.crs = STRICT;
146
+ }
147
+ return out;
148
+ }
149
+
150
+ /**
151
+ * A filter for documents whose index geometry lies inside an area: a
152
+ * Polygon or MultiPolygon, a Feature, or a geotini string. `strict: true`
153
+ * reads a Polygon by its winding, for one larger than a hemisphere.
154
+ */
155
+ export function geoWithin(input, options) {
156
+ return { [fields(options)[1]]: { $geoWithin: { $geometry: area(input, options) } } };
157
+ }
158
+
159
+ /** A filter for documents whose index geometry meets a geometry, a Feature or a geotini string. */
160
+ export function geoIntersects(input, options) {
161
+ return { [fields(options)[1]]: { $geoIntersects: { $geometry: area(input, options) } } };
162
+ }
163
+
164
+ /**
165
+ * A filter that sorts documents by distance from a point, nearest first:
166
+ * [lng, lat], a GeoJSON Point, or a geotini string of one. maxDistance and
167
+ * minDistance are in metres. It needs the 2dsphere index.
168
+ */
169
+ export function near(point, options) {
170
+ let p = Array.isArray(point) ? point : geometryOf(point, reading(options?.decode));
171
+ if (p?.type === 'Feature') p = p.geometry;
172
+ if (p?.type === 'Point') p = p.coordinates;
173
+ if (!Array.isArray(p) || p.length < 2) throw new TypeError('Expected [lng, lat], a Point or a geotini string of one');
174
+ const q = { $geometry: { type: 'Point', coordinates: [p[0], p[1]] } };
175
+ onGlobe(q.$geometry);
176
+ if (options?.maxDistance != null) q.$maxDistance = options.maxDistance;
177
+ if (options?.minDistance != null) q.$minDistance = options.minDistance;
178
+ return { [fields(options)[1]]: { $near: q } };
179
+ }
@@ -0,0 +1,69 @@
1
+ // OpenLayers: a feature format for geotini strings, built on ol/format/GeoJSON.
2
+ //
3
+ // import GeoJSON from 'ol/format/GeoJSON.js';
4
+ // import { createGeotiniFormat } from '@duoquote/geotini/openlayers';
5
+ // const Geotini = createGeotiniFormat({ GeoJSON });
6
+ // const format = new Geotini({ precision: 6, featureProjection: 'EPSG:3857' });
7
+ // const feature = format.readFeature(str); // any geometry type
8
+ // const back = format.writeFeature(feature); // a string again
9
+ //
10
+ // The factory takes ol's GeoJSON class from you instead of importing ol, so
11
+ // geotini has no runtime dependency on it. The class it returns extends that
12
+ // GeoJSON class: strings go in and out where GeoJSON text or objects would,
13
+ // and the rest is ol's own code, projections included (dataProjection is
14
+ // EPSG:4326, as geotini strings are always longitude and latitude).
15
+ //
16
+ // Decoder options go in the constructor under `decode`, apart from encode's
17
+ // options, because `checksum` means something else on each side.
18
+ //
19
+ // Strings carry geometry only: properties, ids and feature names are left
20
+ // out when writing. writeFeatures writes one GeometryCollection string, even
21
+ // for one feature. ol has no empty geometries: an empty Point, LineString,
22
+ // Polygon or MultiPoint reads as null, and drops out of a collection.
23
+ /* @ts-self-types="../types/openlayers.d.ts" */
24
+ import { encode, decode } from './geotini.js';
25
+
26
+ const KEYS = ['precision', 'zPrecision', 'mPrecision', 'checksum', 'favor'];
27
+
28
+ /** A subclass of the ol/format/GeoJSON class you pass that reads and writes geotini strings. */
29
+ export function createGeotiniFormat({ GeoJSON }) {
30
+ return class GeotiniFormat extends GeoJSON {
31
+ /**
32
+ * ol GeoJSON's options (featureProjection, geometryName, ...) plus
33
+ * encode's: precision, zPrecision, mPrecision, checksum and favor, and
34
+ * `decode`: decode's options (checksum, maxLength, maxPositions) for
35
+ * every string read.
36
+ */
37
+ constructor(options = {}) {
38
+ super(options);
39
+ this.encodeOptions = {};
40
+ for (const k of KEYS) if (options[k] !== undefined) this.encodeOptions[k] = options[k];
41
+ this.decodeOptions = options.decode;
42
+ }
43
+ readGeometry(source, options) {
44
+ return super.readGeometry(typeof source == 'string' ? decode(source, this.decodeOptions) : source, options);
45
+ }
46
+ readFeature(source, options) {
47
+ return super.readFeature(typeof source == 'string' ? { type: 'Feature', geometry: decode(source, this.decodeOptions), properties: null } : source, options);
48
+ }
49
+ /** One feature from a string, one per string from an array, or what ol's GeoJSON reads from anything else. */
50
+ readFeatures(source, options) {
51
+ if (typeof source == 'string') return [this.readFeature(source, options)];
52
+ if (Array.isArray(source) && source.every((s) => typeof s == 'string')) return source.map((s) => this.readFeature(s, options));
53
+ return super.readFeatures(source, options);
54
+ }
55
+ writeGeometry(geometry, options) {
56
+ return encode(this.writeGeometryObject(geometry, options), this.encodeOptions);
57
+ }
58
+ writeFeature(feature, options) {
59
+ const g = feature.getGeometry();
60
+ if (!g) throw new TypeError('The feature has no geometry');
61
+ return this.writeGeometry(g, options);
62
+ }
63
+ writeFeatures(features, options) {
64
+ const geometries = features.map((f) => f.getGeometry()).filter(Boolean).map((g) => this.writeGeometryObject(g, options));
65
+ return encode({ type: 'GeometryCollection', geometries }, this.encodeOptions);
66
+ }
67
+ };
68
+ }
69
+