@duoquote/polytini 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.
Files changed (70) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +120 -3
  3. package/dist/deckgl.cjs +250 -0
  4. package/dist/flexible.cjs +229 -0
  5. package/dist/google.cjs +232 -0
  6. package/dist/leaflet-auto.cjs +209 -0
  7. package/dist/leaflet.cjs +231 -0
  8. package/dist/mapbox.cjs +185 -0
  9. package/dist/maplibre.cjs +185 -0
  10. package/dist/node.cjs +322 -0
  11. package/dist/presets.cjs +65 -0
  12. package/dist/turf.cjs +267 -0
  13. package/dist/types/cli.d.cts +2 -0
  14. package/dist/types/deckgl.d.cts +60 -0
  15. package/dist/types/flexible.d.cts +80 -0
  16. package/dist/types/google.d.cts +48 -0
  17. package/dist/types/google.jsr.d.cts +60 -0
  18. package/dist/types/index.d.cts +87 -0
  19. package/dist/types/leaflet-auto.d.cts +4 -0
  20. package/dist/types/leaflet-auto.jsr.d.cts +2 -0
  21. package/dist/types/leaflet.d.cts +39 -0
  22. package/dist/types/leaflet.jsr.d.cts +13 -0
  23. package/dist/types/mapbox.d.cts +50 -0
  24. package/dist/types/maplibre.d.cts +54 -0
  25. package/dist/types/openlayers.d.cts +23 -0
  26. package/dist/types/presets.d.cts +66 -0
  27. package/dist/types/turf.d.cts +33 -0
  28. package/dist/types/wasm.d.cts +33 -0
  29. package/dist/web.cjs +231 -0
  30. package/package.json +200 -6
  31. package/src/browser.js +15 -0
  32. package/src/bun.js +4 -0
  33. package/src/cli-lib.js +160 -0
  34. package/src/cli.js +7 -0
  35. package/src/core.js +268 -0
  36. package/src/deckgl.js +176 -0
  37. package/src/deno.js +12 -0
  38. package/src/error.js +15 -0
  39. package/src/fast.js +179 -0
  40. package/src/flexible.js +283 -0
  41. package/src/google.js +70 -0
  42. package/src/leaflet-auto.js +11 -0
  43. package/src/leaflet.js +44 -0
  44. package/src/mapbox.js +10 -0
  45. package/src/maplibre.js +57 -0
  46. package/src/node.js +17 -0
  47. package/src/openlayers.js +172 -0
  48. package/src/presets.js +242 -0
  49. package/src/text.js +111 -0
  50. package/src/turf.js +80 -0
  51. package/src/wasm-bytes.js +2 -0
  52. package/src/wasm.js +235 -0
  53. package/src/web.js +9 -0
  54. package/types/cli.d.ts +2 -0
  55. package/types/deckgl.d.ts +60 -0
  56. package/types/flexible.d.ts +80 -0
  57. package/types/google.d.ts +48 -0
  58. package/types/google.jsr.d.ts +60 -0
  59. package/types/index.d.ts +87 -0
  60. package/types/leaflet-auto.d.ts +4 -0
  61. package/types/leaflet-auto.jsr.d.ts +2 -0
  62. package/types/leaflet.d.ts +39 -0
  63. package/types/leaflet.jsr.d.ts +13 -0
  64. package/types/mapbox.d.ts +50 -0
  65. package/types/maplibre.d.ts +54 -0
  66. package/types/openlayers.d.ts +23 -0
  67. package/types/presets.d.ts +66 -0
  68. package/types/turf.d.ts +33 -0
  69. package/types/wasm.d.ts +33 -0
  70. package/wasm/polytini.wasm +0 -0
package/src/google.js ADDED
@@ -0,0 +1,70 @@
1
+ // Google Maps JavaScript API helpers: decodePath and encodePath with the
2
+ // signatures of google.maps.geometry.encoding, without loading the geometry
3
+ // library.
4
+ //
5
+ // import { decodePath, encodePath } from '@duoquote/polytini/google';
6
+ // const path = decodePath(route.polyline.encodedPolyline);
7
+ // new google.maps.Polyline({ path, map });
8
+ // encodePath(polyline.getPath()); // an MVCArray<LatLng>
9
+ //
10
+ // Differences from google.maps.geometry.encoding:
11
+ // - Both take an optional second argument: polytini's precision (a number)
12
+ // or options object. Precision defaults to 5, Google's fixed value.
13
+ // - decodePath returns google.maps.LatLng objects when a LatLng constructor
14
+ // is available (the LatLng option, else globalThis.google.maps.LatLng),
15
+ // and plain { lat, lng } literals otherwise, so it also works in Node or
16
+ // before the Maps API has loaded. Pass `LatLng: false` for literals even
17
+ // when the API is loaded. Polyline, Polygon and most Maps API methods
18
+ // take literals as well as LatLng, and literals are cheaper to create.
19
+ // - Strict by default: malformed strings and invalid coordinates throw a
20
+ // PolylineError. Google documents no error behavior for decodePath or
21
+ // encodePath, so what they return for such input can't be matched; a
22
+ // thrown error is easier to find than a wrong line on the map, and valid
23
+ // input gives the same result either way. Pass `strict: false` to never
24
+ // throw on bad characters or truncated strings (invalid characters are
25
+ // skipped and an incomplete last point is dropped) or on invalid
26
+ // coordinates (encoded as 0).
27
+ // - encodePath also takes polytini's [lat, lng] tuples and encodes
28
+ // LatLngLiteral values as given, without clamping or wrapping them.
29
+ /* @ts-self-types="../types/google.jsr.d.ts" */
30
+ import { decode, encode } from './web.js';
31
+
32
+ export { PolylineError } from './web.js';
33
+
34
+ // decodePath reads the tuples as [lat, lng], so it ignores order 'lnglat'.
35
+ const latFirst = (o) => (o?.order == 'lnglat' ? { ...o, order: 'latlng' } : o);
36
+
37
+ /**
38
+ * Decodes an encoded path to google.maps.LatLng objects, or to LatLngLiteral
39
+ * objects when no LatLng constructor is available. Options: polytini's
40
+ * (precision, strict, factor, dimensions), plus `LatLng` (a constructor, or
41
+ * false for literals) and `noClampNoWrap` (passed to the LatLng constructor;
42
+ * without it, Google's LatLng clamps latitude and wraps longitude 180 to -180).
43
+ */
44
+ export function decodePath(encodedPath, o) {
45
+ // o is a number, an options object or undefined; o?.x reads all three.
46
+ const C = o?.LatLng !== undefined ? o.LatLng : globalThis.google?.maps?.LatLng;
47
+ const pts = decode(encodedPath, latFirst(o)), nw = o?.noClampNoWrap;
48
+ for (let i = 0; i < pts.length; i++) {
49
+ const [lat, lng] = pts[i];
50
+ pts[i] = C ? new C(lat, lng, nw) : { lat, lng };
51
+ }
52
+ return pts;
53
+ }
54
+
55
+ /**
56
+ * Encodes an array or MVCArray of google.maps.LatLng objects, LatLngLiteral
57
+ * objects or [lat, lng] tuples (mixed is fine). Options: polytini's
58
+ * (precision, strict, factor, dimensions, and order for tuples and LatLng
59
+ * objects; literals are read by name).
60
+ */
61
+ export function encodePath(path, o) {
62
+ if (path && typeof path.getArray == 'function') path = path.getArray();
63
+ if (Array.isArray(path)) {
64
+ const sw = o?.order == 'lnglat';
65
+ // LatLng objects have lat() and lng() methods; the core reads literals
66
+ // and tuples directly.
67
+ path = path.map((p) => (p && typeof p.lat == 'function' ? (sw ? [p.lng(), p.lat()] : [p.lat(), p.lng()]) : p));
68
+ }
69
+ return encode(path, o);
70
+ }
@@ -0,0 +1,11 @@
1
+ // Side-effect import: patches the global L (Leaflet's UMD build sets it).
2
+ // import 'leaflet';
3
+ // import '@duoquote/polytini/leaflet/auto';
4
+ // For ES module imports of Leaflet, and Leaflet 2, call install(L) from
5
+ // @duoquote/polytini/leaflet instead.
6
+ /* @ts-self-types="../types/leaflet-auto.jsr.d.ts" */
7
+ import { install } from './leaflet.js';
8
+
9
+ const L = globalThis.L;
10
+ if (!L?.Polyline) throw new Error('@duoquote/polytini/leaflet/auto: load Leaflet first, or call install(L) from @duoquote/polytini/leaflet');
11
+ install(L);
package/src/leaflet.js ADDED
@@ -0,0 +1,44 @@
1
+ // Leaflet plugin: encoded polylines in and out of L.Polyline and L.Polygon.
2
+ //
3
+ // import L from 'leaflet';
4
+ // import { install } from '@duoquote/polytini/leaflet';
5
+ // install(L);
6
+ // L.Polyline.fromEncoded('_p~iF~ps|U_ulLnnqC_mqNvxq`@', { color: 'red' }).addTo(map);
7
+ //
8
+ // Works with Leaflet 1.9 (the global L, the UMD build or ESM imports) and the
9
+ // Leaflet 2 betas, where L is a frozen module namespace of ES classes: there
10
+ // the static and prototype methods are added, and the lower-case factories
11
+ // are skipped because the namespace can't take new properties.
12
+ //
13
+ // It also covers the API of the old Polyline.encoded.js plugin (npm
14
+ // polyline-encoded): L.Polyline.fromEncoded, L.Polygon.fromEncoded,
15
+ // encodePath() and L.PolylineUtil, so it can replace it.
16
+ /* @ts-self-types="../types/leaflet.jsr.d.ts" */
17
+ import { encode, decode } from './web.js';
18
+
19
+ // One string decodes to one line or ring, arrays nest: string[] is a
20
+ // multi-polyline or a polygon with holes, string[][] a multi-polygon.
21
+ const toLatLngs = (s, o) => (typeof s == 'string' ? decode(s, o) : s.map((x) => toLatLngs(x, o)));
22
+
23
+ // The reverse, from getLatLngs(): LatLng[] encodes to a string, nested arrays
24
+ // to nested arrays of strings.
25
+ const toStrings = (l, o) => (Array.isArray(l[0]) ? l.map((x) => toStrings(x, o)) : encode(l.map((p) => [p.lat, p.lng]), o));
26
+
27
+ export function install(L) {
28
+ const { Polyline, Polygon } = L;
29
+ const add = (C, name) => {
30
+ C.fromEncoded = (s, o) => new C(toLatLngs(s, o), o);
31
+ C.prototype.toEncoded = function (o) {
32
+ return toStrings(this.getLatLngs(), o);
33
+ };
34
+ // Polyline.encoded.js name.
35
+ C.prototype.encodePath = C.prototype.toEncoded;
36
+ if (Object.isExtensible(L)) L[name] = C.fromEncoded;
37
+ };
38
+ add(Polyline, 'polylineEncoded');
39
+ add(Polygon, 'polygonEncoded');
40
+ if (Object.isExtensible(L)) L.PolylineUtil ??= { encode, decode };
41
+ return L;
42
+ }
43
+
44
+ export { encode, decode };
package/src/mapbox.js ADDED
@@ -0,0 +1,10 @@
1
+ // Mapbox GL JS 3: the same functions as the MapLibre module. The calls they
2
+ // make (addSource with a GeoJSON source specification, addLayer with a line
3
+ // layer and a beforeId, getSource(id).setData) take the same arguments in
4
+ // both libraries, so only the types differ: types/mapbox.d.ts uses
5
+ // mapbox-gl's.
6
+ //
7
+ // import { addPolylineLayer } from '@duoquote/polytini/mapbox';
8
+ // map.on('load', () => addPolylineLayer(map, 'route', encoded, { layer: { paint: { 'line-color': '#c00' } } }));
9
+ /* @ts-self-types="../types/mapbox.d.ts" */
10
+ export { polylineData, polylineSource, addPolylineLayer, setPolylineData } from './maplibre.js';
@@ -0,0 +1,57 @@
1
+ // MapLibre GL JS (and Mapbox GL JS, see mapbox.js): encoded polylines as
2
+ // GeoJSON sources and line layers.
3
+ //
4
+ // import { addPolylineLayer, setPolylineData } from '@duoquote/polytini/maplibre';
5
+ // map.on('load', () => {
6
+ // addPolylineLayer(map, 'route', route.geometry, { precision: 6, layer: { paint: { 'line-width': 4 } } });
7
+ // });
8
+ // setPolylineData(map, 'route', newRoute.geometry, { precision: 6 });
9
+ //
10
+ // No map library code is imported: the functions only call addSource,
11
+ // addLayer and getSource(id).setData on the map they are given, which
12
+ // MapLibre GL 4 to 6 and Mapbox GL 3 all have with the same arguments.
13
+ // Coordinates come out as [lng, lat] like all GeoJSON, whatever `order` the
14
+ // options or a preset say.
15
+ /* @ts-self-types="../types/maplibre.d.ts" */
16
+ import { toFeatureCollection } from './turf.js';
17
+ import { fail } from './core.js';
18
+
19
+ const list = (encoded) => (typeof encoded == 'string' ? [encoded] : encoded);
20
+
21
+ /**
22
+ * The FeatureCollection<LineString> for one encoded string or many.
23
+ * Options: polytini options or a preset, plus `properties` and `id` (one
24
+ * value for all lines or an array with one per line) and `bbox`.
25
+ */
26
+ export const polylineData = (encoded, options) => toFeatureCollection(list(encoded), options);
27
+
28
+ /**
29
+ * A GeoJSON source specification, `{ type: 'geojson', data }`, for addSource
30
+ * or a style's `sources`. `options.source` adds source options such as
31
+ * lineMetrics, tolerance or promoteId.
32
+ */
33
+ export const polylineSource = (encoded, options) => ({ ...options?.source, type: 'geojson', data: polylineData(encoded, options) });
34
+
35
+ /**
36
+ * Adds a GeoJSON source and a line layer that draws it, both named `id`.
37
+ * `options.layer` is merged into the layer (paint, layout, filter, minzoom,
38
+ * a different id, and so on), and `options.beforeId` is passed to addLayer.
39
+ * Returns the map.
40
+ */
41
+ export function addPolylineLayer(map, id, encoded, options) {
42
+ map.addSource(id, polylineSource(encoded, options));
43
+ map.addLayer({ id, type: 'line', source: id, ...options?.layer }, options?.beforeId);
44
+ return map;
45
+ }
46
+
47
+ /**
48
+ * Replaces the data of the GeoJSON source `id` with new lines and returns
49
+ * what the source's setData returns (a Promise in MapLibre, the source in
50
+ * Mapbox). Throws a PolylineError with code 'input' if there is no such
51
+ * GeoJSON source.
52
+ */
53
+ export function setPolylineData(map, id, encoded, options) {
54
+ const source = map.getSource(id);
55
+ if (typeof source?.setData != 'function') fail('input', 'No GeoJSON source named ' + id);
56
+ return source.setData(polylineData(encoded, options));
57
+ }
package/src/node.js ADDED
@@ -0,0 +1,17 @@
1
+ // Node entry: the core plus the Buffer fast paths in fast.js.
2
+ /* @ts-self-types="../types/index.d.ts" */
3
+ import { Buffer } from 'node:buffer';
4
+ import { fast } from './fast.js';
5
+ import { latLngs, toGeo, fromGeo } from './core.js';
6
+
7
+ export { PolylineError } from './core.js';
8
+ // On V8 12 (Node 22 and 23), a pre-sized array of 100,000 points made decode
9
+ // about 40% slower than appending. Probably because the big array lands in
10
+ // old space and every young point stored into it goes through the write
11
+ // barrier, but I haven't profiled the GC to confirm it. V8 13
12
+ // and 14 (Node 24 on, and what Bun reports) were 25% faster pre-sized, so
13
+ // only V8 12 appends, from 32,768 points.
14
+ export const { decode, decodeFlat, encode, encodeFlat } = fast(Buffer, process.versions.v8?.startsWith('12.') ? 32768 : Infinity);
15
+ export const decodeLatLng = latLngs(decode);
16
+ export const toGeoJSON = toGeo(decode);
17
+ export const fromGeoJSON = fromGeo(encode);
@@ -0,0 +1,172 @@
1
+ // OpenLayers: a faster drop-in for ol/format/Polyline.
2
+ //
3
+ // import Polyline from 'ol/format/Polyline.js';
4
+ // import LineString from 'ol/geom/LineString.js';
5
+ // import { createPolylineFormat } from '@duoquote/polytini/openlayers';
6
+ // const FastPolyline = createPolylineFormat({ Polyline, LineString });
7
+ // const format = new FastPolyline({ factor: 1e6 });
8
+ //
9
+ // The factory takes ol's classes from you instead of importing ol, so
10
+ // polytini has no runtime dependency on it. The class it returns extends
11
+ // the Polyline class you pass and replaces only the two text-level methods,
12
+ // readGeometryFromText and writeGeometryText. Everything else is ol's: the
13
+ // constructor options (factor, geometryLayout), projections, readFeature,
14
+ // readFeatures, writeFeature, writeFeatures and the `decimals` write option.
15
+ //
16
+ // The output is the same as ol's for every input, with one exception: ol's
17
+ // writeGeometry flips XY and writes the deltas into the geometry's own flat
18
+ // coordinates when there is no projection transform (and no `decimals`), so
19
+ // a second writeGeometry of the same geometry gives a wrong string. This
20
+ // class never changes the geometry.
21
+ //
22
+ // What "the same" means in detail:
23
+ // - Coordinates come out as [x, y] = [lng, lat], then Z and M, as plain
24
+ // arrays, and every value, M included, is divided by the factor. A factor
25
+ // of 0 or no factor means 1e5, like ol.
26
+ // - Rounding is ol's, not Google's. ol rounds with
27
+ // `value < 0 ? Math.ceil(value - 0.5) : Math.round(value)`. That is half
28
+ // away from zero for every value except -0.49999999999999994 (the largest
29
+ // double below 0.5, negated), where `value - 0.5` rounds to -1 in floating
30
+ // point, so ol writes -1 where Google's algorithm, and polytini's own
31
+ // encode, write 0. (Values of 2^52 and more differ too, but those are past
32
+ // ol's 32-bit limit anyway.) A drop-in should give the same strings as the
33
+ // format it replaces, so this class rounds like ol.
34
+ // - ol never throws on bad input. Strings that are not plain valid polylines
35
+ // (characters outside '?' to '~', a value cut off at the end, a point with
36
+ // fewer values than the layout has, or a value of more than 30 bits) and
37
+ // geometries with values that do not fit 32-bit deltas (NaN, Infinity, or
38
+ // deltas of 2^29 units or more) are handed to ol's own code, so they give
39
+ // exactly what ol gives, odd results included: a NaN for a missing value,
40
+ // and 32-bit wrap-around for very large values.
41
+ /* @ts-self-types="../types/openlayers.d.ts" */
42
+ import { chars, LIMIT } from './core.js';
43
+
44
+ const STRIDE = { XY: 2, XYZ: 3, XYM: 3, XYZM: 4 };
45
+
46
+ // Encoded characters for zigzag values below 1024.
47
+ const CHARS = [];
48
+ for (let z = 0; z < 1024; z++) CHARS[z] = chars(z);
49
+
50
+ /**
51
+ * Decodes to ol's flat coordinates ([lng, lat, ...rest] per point), or
52
+ * returns null when the string is anything but a plain valid polyline with
53
+ * a whole number of points and values of at most 6 characters. On those
54
+ * strings ol's 32-bit math is exact, so the result is identical to ol's.
55
+ */
56
+ function decodeFlat(str, stride, f) {
57
+ if (!(stride >= 2 && stride <= 4)) return null;
58
+ const len = str.length, sum = [0, 0, 0, 0];
59
+ let i = 0, n = 0, bad = 0, d, c, v, s;
60
+ // Long lines are counted first (every value ends with exactly one
61
+ // character below code 95) and get one array of the right size: growing
62
+ // an array of a few hundred thousand doubles was slower than the extra
63
+ // pass. Short ones grow by appending, which was faster for them.
64
+ if (len > 50000) for (; i < len; i++) n += (str.charCodeAt(i) - 95) >>> 31;
65
+ const out = n ? new Array(n) : [];
66
+ i = n = 0;
67
+ while (i < len) {
68
+ for (d = 0; d < stride; d++) {
69
+ // Past the end, charCodeAt gives NaN: the value ends and i passes len.
70
+ c = str.charCodeAt(i++) - 63;
71
+ bad |= c;
72
+ v = c & 31;
73
+ for (s = 5; c >= 32; s += 5) {
74
+ c = str.charCodeAt(i++) - 63;
75
+ bad |= c;
76
+ v |= (c & 31) << s;
77
+ }
78
+ bad |= 30 - s;
79
+ sum[d] += (v >>> 1) ^ -(v & 1);
80
+ }
81
+ out[n++] = sum[1] / f;
82
+ out[n++] = sum[0] / f;
83
+ if (stride > 2) out[n++] = sum[2] / f;
84
+ if (stride > 3) out[n++] = sum[3] / f;
85
+ }
86
+ return bad & ~63 || i != len ? null : out;
87
+ }
88
+
89
+ /**
90
+ * Encodes ol flat coordinates without changing them, rounding like ol.
91
+ * Returns null when a delta is not finite or too large for 32-bit math, or
92
+ * the length is not a whole number of points.
93
+ */
94
+ function encodeFlat(flat, stride, f) {
95
+ const n = flat.length, last = [0, 0, 0, 0];
96
+ if (n % stride) return null;
97
+ let s = '', k = 0, d, v, z;
98
+ for (; k < n; k += stride) {
99
+ for (d = 0; d < stride; d++) {
100
+ v = flat[k + (d < 2 ? 1 - d : d)] * f;
101
+ v = v < 0 ? Math.ceil(v - 0.5) : Math.round(v);
102
+ z = v - last[d];
103
+ last[d] = v;
104
+ if (!(z < LIMIT && z > -LIMIT)) return null;
105
+ z = (z << 1) ^ (z >> 31);
106
+ s += z < 1024 ? CHARS[z] : chars(z);
107
+ }
108
+ }
109
+ return s;
110
+ }
111
+
112
+ // The projection step of ol's format, done with the geometry's own
113
+ // transform() so nothing from ol has to be imported. Returns null when ol
114
+ // has to do it itself: tile-pixel projections, which ol handles specially.
115
+ const projections = (options, write) => {
116
+ const fp = options?.featureProjection, dp = options?.dataProjection;
117
+ const tile = (p) => typeof p == 'object' && p?.getUnits?.() == 'tile-pixels';
118
+ if (tile(fp) || tile(dp)) return null;
119
+ // Equal codes need nothing. Different but equivalent projections
120
+ // (EPSG:3857 and EPSG:900913) go through transform(), which copies the
121
+ // values unchanged, so the numbers are the same as ol's.
122
+ return fp && dp && fp !== dp ? (write ? [fp, dp] : [dp, fp]) : [];
123
+ };
124
+
125
+ /**
126
+ * Makes the drop-in class from ol's own. Pass `{ Polyline, LineString }`
127
+ * (ol/format/Polyline.js and ol/geom/LineString.js), or the `ol` namespace
128
+ * of the full build.
129
+ */
130
+ export function createPolylineFormat(ol) {
131
+ const Base = ol?.Polyline ?? ol?.format?.Polyline, LineString = ol?.LineString ?? ol?.geom?.LineString;
132
+ if (typeof Base != 'function' || typeof LineString != 'function') {
133
+ throw new TypeError('createPolylineFormat needs { Polyline, LineString } from ol');
134
+ }
135
+ /** Drop-in for ol/format/Polyline: same options and output, faster, and it never changes the geometry it writes. */
136
+ return class Polyline extends Base {
137
+ constructor(options) {
138
+ super(options);
139
+ options = options || {};
140
+ // ol keeps these as private fields; keep our own copies.
141
+ this.polyFactor_ = options.factor ? options.factor : 1e5;
142
+ this.polyLayout_ = options.geometryLayout ? options.geometryLayout : 'XY';
143
+ }
144
+
145
+ readGeometryFromText(text, options) {
146
+ options = this.adaptOptions(options);
147
+ const layout = this.polyLayout_, p = projections(options, false);
148
+ const flat = p && decodeFlat(text, STRIDE[layout], this.polyFactor_);
149
+ if (!flat) return super.readGeometryFromText(text, options);
150
+ const geometry = new LineString(flat, layout);
151
+ return p.length ? geometry.transform(p[0], p[1]) : geometry;
152
+ }
153
+
154
+ writeGeometryText(geometry, options) {
155
+ options = this.adaptOptions(options);
156
+ const p = projections(options, true);
157
+ let flat = geometry.getFlatCoordinates();
158
+ const stride = geometry.getStride(), f = this.polyFactor_;
159
+ if (p) {
160
+ if (p.length) flat = geometry.clone().transform(p[0], p[1]).getFlatCoordinates();
161
+ // ol's `decimals`: round every value to that many places first.
162
+ if (options?.decimals !== undefined) {
163
+ const power = Math.pow(10, options.decimals);
164
+ flat = flat.map((c) => Math.round(c * power) / power);
165
+ }
166
+ }
167
+ // Anything else goes to ol's own writer, on a copy: it writes the
168
+ // deltas into the geometry it encodes.
169
+ return (p && encodeFlat(flat, stride, f)) ?? super.writeGeometryText(geometry.clone(), options);
170
+ }
171
+ };
172
+ }
package/src/presets.js ADDED
@@ -0,0 +1,242 @@
1
+ // Option presets for routing engines and APIs that use the Google encoded
2
+ // polyline format. Each preset is a plain options object for encode, decode,
3
+ // encodeFlat, decodeFlat, toGeoJSON and fromGeoJSON:
4
+ //
5
+ // import { decode } from '@duoquote/polytini';
6
+ // import { osrm6 } from '@duoquote/polytini/presets';
7
+ // decode(route.geometry, osrm6); // [[lng, lat], ...]
8
+ //
9
+ // This module imports nothing, so it adds no bytes to the codec, and a
10
+ // bundler keeps only the presets you import.
11
+ //
12
+ // How the values were chosen:
13
+ //
14
+ // - precision: the engine's documented precision, checked against its
15
+ // encoder source where the source is public. Presets use `precision`
16
+ // rather than `factor`, so spreading a preset and adding `factor` (for
17
+ // example GraphHopper's points_encoded_multiplier) still works, because
18
+ // factor takes priority over precision.
19
+ // - order: the order of the engine's own unencoded coordinates (GeoJSON or
20
+ // coordinate arrays), so decoded output can be compared with, or used in
21
+ // place of, what the engine returns when you ask it for plain coordinates.
22
+ // The encoded string always stores latitude first; order only changes the
23
+ // tuples you pass in and get back. Override it with a spread, for example
24
+ // { ...valhalla, order: 'latlng' }.
25
+ // - dimensions and zFactor: only for engines that put a third value in the
26
+ // string. Those engines only add it when asked, so each has a 2D preset
27
+ // for the default response and a "3d" preset for the elevation response.
28
+ // A 3D preset on a 2D string throws in strict mode when the value count is
29
+ // not a multiple of 3, and gives wrong points when it is, so pick the
30
+ // preset that matches the request.
31
+ //
32
+ // Rounding: polytini rounds half away from zero, like Google's description
33
+ // and like OSRM and Valhalla (C++ std::round / round). Java's Math.round,
34
+ // used by GraphHopper and openrouteservice, rounds halves toward positive
35
+ // infinity, and some engines floor. This only matters when encoding:
36
+ // decoding gives the engine's exact values for every preset. The core has
37
+ // no rounding option, so where an engine rounds differently, encoding a
38
+ // point with its preset can give a string that differs from the engine's
39
+ // own output by one unit in the last place for some inputs. Each preset
40
+ // below says when that happens.
41
+ //
42
+ // Not covered here, because they are not the Google algorithm:
43
+ // - HERE flexible polyline (a header with precision and a third dimension
44
+ // type, and a different character table). Use '@duoquote/polytini/flexible'.
45
+ // - Bing Maps point compression (each latitude and longitude pair is
46
+ // combined into one value, and it uses a different character table):
47
+ // https://learn.microsoft.com/en-us/bingmaps/rest-services/elevations/point-compression-algorithm
48
+ //
49
+ // Sources were read on 2026-11-26. Commits are the default branch heads on
50
+ // that date.
51
+ /* @ts-self-types="../types/presets.d.ts" */
52
+
53
+ /**
54
+ * Google Maps Platform: the format's own definition, precision 5.
55
+ * https://developers.google.com/maps/documentation/utilities/polylinealgorithm
56
+ *
57
+ * order 'latlng': Google's decoders return latitude first:
58
+ * google.maps.geometry.encoding.decodePath returns Array<LatLng>
59
+ * (https://developers.google.com/maps/documentation/javascript/reference/geometry),
60
+ * and Directions API locations are {lat, lng}. The Routes API can also
61
+ * return GeoJSON ([lng, lat]) with polylineEncoding: GEO_JSON_LINESTRING
62
+ * (https://developers.google.com/maps/documentation/routes/traffic_on_polylines);
63
+ * use { ...google, order: 'lnglat' } to compare with that.
64
+ */
65
+ export const google = { precision: 5, order: 'latlng' };
66
+
67
+ /**
68
+ * OSRM, geometries=polyline (the default), precision 5.
69
+ * Docs: https://github.com/Project-OSRM/osrm-backend/blob/578a12065917e02bf14bb4568f12a2d3c388ba15/docs/http.md
70
+ * ("polyline with precision 5 in [latitude,longitude] encoding"; also
71
+ * http://project-osrm.org/docs/v5.24.0/api/).
72
+ * Encoder: include/engine/polyline_compressor.hpp at the same commit.
73
+ * OSRM stores coordinates as integers at 1e6 and encodes
74
+ * std::round(fixed * 0.1), which rounds half away from zero, as polytini
75
+ * does.
76
+ *
77
+ * order 'lnglat': geometries=geojson returns a GeoJSON LineString, and
78
+ * waypoint, maneuver and intersection locations are [longitude, latitude].
79
+ * The tests check the public demo server's polyline against its GeoJSON.
80
+ */
81
+ export const osrm = { precision: 5, order: 'lnglat' };
82
+
83
+ /** OSRM, geometries=polyline6: as `osrm`, precision 6. */
84
+ export const osrm6 = { precision: 6, order: 'lnglat' };
85
+
86
+ /**
87
+ * Valhalla, precision 6. The native JSON response has trip.legs[].shape;
88
+ * trace_attributes, height and linear_cost_factors also use precision 6.
89
+ * Docs: https://github.com/valhalla/valhalla/blob/4d8b2061b566412ce61eb8a2001b7cfa2392356a/docs/docs/api/decoding.md
90
+ * ("Valhalla APIs use six digits of decimal precision") and
91
+ * docs/docs/api/route/api-reference.md at the same commit.
92
+ * Encoder: valhalla/midgard/encoded.h at the same commit,
93
+ * round(value * 1e6), half away from zero, latitude first.
94
+ *
95
+ * order 'lnglat': Valhalla's only plain coordinate line output is
96
+ * format=osrm with shape_format=geojson, which is [lng, lat]. Request
97
+ * coordinates are {lat, lon} objects, and the JavaScript example in
98
+ * decoding.md returns [lat, lng]; use { ...valhalla, order: 'latlng' } to
99
+ * match that example.
100
+ *
101
+ * With format=osrm the geometry is polyline6 by default (use this preset or
102
+ * osrm6), or polyline5 with shape_format=polyline5 (use `osrm`).
103
+ */
104
+ export const valhalla = { precision: 6, order: 'lnglat' };
105
+
106
+ /**
107
+ * Stadia Maps routing, which runs Valhalla: precision 6, legs[].shape.
108
+ * https://docs.stadiamaps.com/tutorials/getting-directions-in-javascript-from-geospatial-apis-maplibre
109
+ * ("Our polylines have 6 digits of precision, not 5"; the example decodes
110
+ * leg.shape with polyline.toGeoJSON(shape, 6)). Same values as `valhalla`.
111
+ */
112
+ export const stadia = { precision: 6, order: 'lnglat' };
113
+
114
+ /**
115
+ * GraphHopper, points_encoded=true (the default) and elevation=false (the
116
+ * default): paths[].points and paths[].snapped_waypoints.
117
+ * Docs: https://github.com/graphhopper/graphhopper/blob/ce72e96197eb16fcc3ab4f18fdd543fa270be9d5/docs/web/api-doc.md
118
+ * Encoder: ResponsePathSerializer.encodePolyline in
119
+ * web-api/src/main/java/com/graphhopper/jackson/ResponsePathSerializer.java
120
+ * at the same commit.
121
+ *
122
+ * Latitude and longitude use the points_encoded_multiplier parameter,
123
+ * default 1e5 (web-bundle/.../RouteResource.java), which any value of 1 or
124
+ * more can change. The response echoes it as paths[].points_encoded_multiplier
125
+ * since GraphHopper 9.0 (commit 322be2aa43, "polyline multiplier"). For a
126
+ * response with another multiplier use
127
+ * { ...graphhopper, factor: path.points_encoded_multiplier }.
128
+ * GraphHopper's /navigate endpoint (Mapbox compatible) always uses
129
+ * polyline6; use `mapbox6` there.
130
+ *
131
+ * Rounding: Math.round since GraphHopper 9.0 (commit 4a5dbeb3ff, "encoded
132
+ * polyline algorithm: closer to Google spec"); 8.0 and earlier used
133
+ * Math.floor. Math.round rounds halves toward positive infinity, so a
134
+ * scaled value of exactly -2.5 becomes -2 in GraphHopper and -3 in
135
+ * polytini. Only negative values exactly halfway between two steps differ.
136
+ * The floor of older versions differs from rounding about half the time.
137
+ * Decoding is exact for all versions.
138
+ *
139
+ * order 'lnglat': with points_encoded=false, points is a GeoJSON
140
+ * LineString with [lon, lat, elevation] order.
141
+ */
142
+ export const graphhopper = { precision: 5, order: 'lnglat' };
143
+
144
+ /**
145
+ * GraphHopper with elevation=true: a third value per point, elevation in
146
+ * meters times 100 (hard coded, it does not follow
147
+ * points_encoded_multiplier), so centimeters. Decodes to
148
+ * [lng, lat, elevation]. Same encoder and rounding notes as `graphhopper`:
149
+ * a negative elevation exactly halfway between two centimeters (such as
150
+ * -0.125 m) encodes one centimeter higher in GraphHopper than in polytini.
151
+ */
152
+ export const graphhopper3d = { precision: 5, dimensions: 3, zFactor: 100, order: 'lnglat' };
153
+
154
+ /**
155
+ * openrouteservice, /v2/directions/{profile}/json: routes[].geometry,
156
+ * precision 5. ORS uses its own encoder, not GraphHopper's, and the
157
+ * multiplier is fixed.
158
+ * Docs: https://github.com/GIScience/openrouteservice/blob/65fb57b1d6716ef5147af5d62909402eb51a85f4/docs/api-reference/endpoints/directions/geometry-decoding.md
159
+ * and requests-and-return-types.md in the same folder.
160
+ * Encoder: ors-engine/src/main/java/org/heigit/ors/util/PolylineEncoder.java
161
+ * at the same commit: Math.round(lat * 1e5) and Math.round(lng * 1e5), with
162
+ * the same negative halfway difference as `graphhopper`.
163
+ *
164
+ * order 'lnglat': the geojson endpoint returns a LineString, and request
165
+ * coordinates are longitude/latitude pairs.
166
+ */
167
+ export const openrouteservice = { precision: 5, order: 'lnglat' };
168
+
169
+ /**
170
+ * openrouteservice with elevation=true ("elevation also gets encoded for
171
+ * json response encoded polyline", RouteRequest.java): a third value,
172
+ * elevation in meters times 100. Decodes to [lng, lat, elevation].
173
+ *
174
+ * Rounding: ORS floors the elevation, (long) Math.floor(z * 100), where
175
+ * polytini rounds, so polytini can encode one centimeter more than ORS.
176
+ * That includes some whole-centimeter values, because the multiplication
177
+ * is not exact: 1027.1 * 100 is 102709.99999999999, which ORS stores as
178
+ * 1027.09 m. Latitude and longitude follow the `openrouteservice` notes.
179
+ * Decoding is exact.
180
+ */
181
+ export const openrouteservice3d = { precision: 5, dimensions: 3, zFactor: 100, order: 'lnglat' };
182
+
183
+ /**
184
+ * Mapbox Directions, geometries=polyline (the default), precision 5.
185
+ * Docs: https://docs.mapbox.com/api/navigation/directions/
186
+ * ("polyline (default, a polyline with a precision of five decimal
187
+ * places)"). The encoder is not public; the tests check the response
188
+ * fixtures in mapbox/mapbox-java (MIT).
189
+ *
190
+ * order 'lnglat': geometries=geojson returns a LineString, and waypoint,
191
+ * maneuver and intersection locations are [longitude, latitude].
192
+ */
193
+ export const mapbox = { precision: 5, order: 'lnglat' };
194
+
195
+ /** Mapbox Directions, geometries=polyline6: as `mapbox`, precision 6. */
196
+ export const mapbox6 = { precision: 6, order: 'lnglat' };
197
+
198
+ /**
199
+ * Strava API v3: map.polyline and map.summary_polyline on activities,
200
+ * routes and segments, precision 5.
201
+ * Docs: https://developers.strava.com/docs/reference/ (PolylineMap). The
202
+ * docs do not state the precision; the example summary_polyline there
203
+ * starts at 37.82822, -122.26348 at precision 5, next to the example's
204
+ * start_latlng [37.83, -122.26]. The encoder is not public.
205
+ *
206
+ * order 'latlng': Strava's own coordinates (LatLng, start_latlng, the
207
+ * latlng stream) are [latitude, longitude] arrays.
208
+ */
209
+ export const strava = { precision: 5, order: 'latlng' };
210
+
211
+ /**
212
+ * OpenTripPlanner 2: legGeometry.points in the GraphQL APIs, precision 5.
213
+ * Encoder: street/src/main/java/org/opentripplanner/street/geometry/PolylineEncoder.java
214
+ * and application/src/main/java/org/opentripplanner/api/model/geometry/EncodedPolyline.java
215
+ * in opentripplanner/OpenTripPlanner at 14bcee2a04d0c4a012f524b84b0814595130bf99.
216
+ *
217
+ * Rounding: OTP floors, (int) Math.floor(coordinate * 1e5), so encoding
218
+ * with this preset can give a value one step (1e-5 degrees) higher than
219
+ * OTP's for any point that is not on the 1e-5 grid. Decoding is exact.
220
+ *
221
+ * order 'latlng': OTP has no plain coordinate line output; places and
222
+ * steps give lat and lon as separate fields. The preset keeps the string's
223
+ * own latitude first order.
224
+ */
225
+ export const otp = { precision: 5, order: 'latlng' };
226
+
227
+ /** Every preset, keyed by its export name. */
228
+ export const presets = {
229
+ google,
230
+ osrm,
231
+ osrm6,
232
+ valhalla,
233
+ stadia,
234
+ graphhopper,
235
+ graphhopper3d,
236
+ openrouteservice,
237
+ openrouteservice3d,
238
+ mapbox,
239
+ mapbox6,
240
+ strava,
241
+ otp,
242
+ };