@itowns/geographic 2.44.2

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.
@@ -0,0 +1,364 @@
1
+ import * as THREE from 'three';
2
+ import proj4 from 'proj4';
3
+ import Ellipsoid from 'Ellipsoid';
4
+ import * as CRS from './Crs';
5
+
6
+ import type { ProjectionLike } from './Crs';
7
+
8
+ const ellipsoid = new Ellipsoid();
9
+ const projectionCache: Record<string, Record<string, proj4.Converter>> = {};
10
+
11
+ const v0 = new THREE.Vector3();
12
+ const v1 = new THREE.Vector3();
13
+
14
+ let coord0: Coordinates;
15
+ let coord1: Coordinates;
16
+
17
+ export interface CoordinatesLike {
18
+ readonly crs: string;
19
+ readonly x: number;
20
+ readonly y: number;
21
+ readonly z: number;
22
+ }
23
+
24
+ function proj4cache(crsIn: string, crsOut: string): proj4.Converter {
25
+ if (!projectionCache[crsIn]) {
26
+ projectionCache[crsIn] = {};
27
+ }
28
+
29
+ if (!projectionCache[crsIn][crsOut]) {
30
+ projectionCache[crsIn][crsOut] = proj4(crsIn, crsOut);
31
+ }
32
+
33
+ return projectionCache[crsIn][crsOut];
34
+ }
35
+
36
+ /**
37
+ * A class representing a geographic or geocentric coordinate.
38
+ *
39
+ * A coordinate is defined by a [CRS](http://inspire.ec.europa.eu/theme/rs)
40
+ * (Coordinate Reference System) and a 3-dimensional vector `(x, y, z)`.
41
+ * For geocentric projections, it is recommended to use the `latitude`,
42
+ * `longitude` and `altitude` aliases to refer to vector components.
43
+ *
44
+ * To change a value, prefer the use of the `set*` methods.
45
+ *
46
+ * By default, the `EPSG:4978` and `EPSG:4326` projections are supported. To use
47
+ * a different projection, it must have been declared previously with `proj4`.
48
+ * A comprehensive list of projections and their corresponding proj4 string can
49
+ * be found at [epsg.io](https://epsg.io/).
50
+ *
51
+ * @example Geocentric coordinates
52
+ * ```js
53
+ * new Coordinates('EPSG:4978', 20885167, 849862, 23385912);
54
+ * ```
55
+ *
56
+ * @example Geographic coordinates
57
+ * ```js
58
+ * new Coordinates('EPSG:4326', 2.33, 48.24, 24999549);
59
+ * ```
60
+ *
61
+ * @example Defining the EPSG:2154 projection with proj4
62
+ * ```js
63
+ * proj4.defs('EPSG:2154', `+proj=lcc +lat_0=46.5 +lon_0=3 +lat_1=49 +lat_2=44
64
+ * +x_0=700000 +y_0=6600000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m
65
+ * +no_defs +type=crs`);
66
+ * ```
67
+ */
68
+ class Coordinates {
69
+ /**
70
+ * Read-only flag to check if a given object is of type `Coordinates`.
71
+ */
72
+ readonly isCoordinates: boolean;
73
+ /**
74
+ * A default or user-defined CRS (see {@link ProjectionLike}).
75
+ */
76
+ crs: ProjectionLike;
77
+
78
+ /** The x value (or longitude) of this coordinate. */
79
+ x: number;
80
+ /** The y value (or latitude) of this coordinate. */
81
+ y: number;
82
+ /** The z value (or altitude) of this coordinate. */
83
+ z: number;
84
+
85
+ private _normal: THREE.Vector3;
86
+ private _normalNeedsUpdate: boolean;
87
+
88
+ /**
89
+ * @param crs - A default or user-defined CRS (see {@link ProjectionLike}).
90
+ * @param x - x or longitude value.
91
+ * @param y - y or latitude value.
92
+ * @param z - z or altitude value.
93
+ */
94
+ constructor(crs: ProjectionLike, x: number = 0, y: number = 0, z: number = 0) {
95
+ this.isCoordinates = true;
96
+
97
+ CRS.isValid(crs);
98
+ this.crs = crs;
99
+
100
+ // Storing the coordinates as is, not in arrays, as it is
101
+ // slower (see https://jsbench.me/40jumfag6g/1)
102
+ this.x = 0;
103
+ this.y = 0;
104
+ this.z = 0;
105
+
106
+ // Normal
107
+ this._normal = new THREE.Vector3();
108
+
109
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
110
+ if ((x as any).length > 0) { // deepscan-disable-line
111
+ console.warn(
112
+ 'Deprecated Coordinates#constructor(string, number[]),',
113
+ 'use `new Coordinates(string).setFromArray(number[])` instead.',
114
+ );
115
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
116
+ this.setFromArray(x as any);
117
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
118
+ } else if ((x as any).isVector3 || (x as any).isCoordinates) {
119
+ console.warn(
120
+ 'Deprecated Coordinates#constructor(string, Vector3),',
121
+ 'use `new Coordinates(string).setFromVector3(Vector3)` instead.',
122
+ );
123
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
124
+ this.setFromVector3(x as any);
125
+ } else {
126
+ this.setFromValues(x, y, z);
127
+ }
128
+
129
+ this._normalNeedsUpdate = true;
130
+ }
131
+
132
+ /**
133
+ * Sets the Coordinate Reference System.
134
+ * @param crs - Coordinate Reference System (e.g. 'EPSG:4978')
135
+ */
136
+ setCrs(crs: ProjectionLike): this {
137
+ CRS.isValid(crs);
138
+ this.crs = crs;
139
+ return this;
140
+ }
141
+
142
+ /**
143
+ * Sets the x, y and z components of this coordinate.
144
+ *
145
+ * @param x - x or longitude value.
146
+ * @param y - y or latitude value.
147
+ * @param z - z or altitude value.
148
+ */
149
+ setFromValues(x: number = 0, y: number = 0, z: number = 0): this {
150
+ this.x = x;
151
+ this.y = y;
152
+ this.z = z;
153
+
154
+ this._normalNeedsUpdate = true;
155
+ return this;
156
+ }
157
+
158
+ /**
159
+ * Sets the coordinates's {@link Coordinates#x | x} component to
160
+ * `array[offset + 0]`, {@link Coordinates#y | y} component to
161
+ * `array[offset + 1]` and {@link Coordinates#z | z} component to
162
+ * `array[offset + 2]`.
163
+ *
164
+ * @param array - The source array.
165
+ * @param offset - Optional offset into the array. Default is 0.
166
+ */
167
+ setFromArray(array: number[], offset: number = 0): this {
168
+ return this.setFromValues(
169
+ array[offset],
170
+ array[offset + 1],
171
+ array[offset + 2],
172
+ );
173
+ }
174
+
175
+ /**
176
+ * Sets the `(x, y, z)` vector of this coordinate from a 3-dimensional
177
+ * vector-like object. This object shall have both `x`, `y` and `z`
178
+ * properties.
179
+ *
180
+ * @param v - The source object.
181
+ */
182
+ setFromVector3(v: THREE.Vector3Like): this {
183
+ return this.setFromValues(v.x, v.y, v.z);
184
+ }
185
+
186
+ /**
187
+ * Returns a new coordinate with the same `(x, y, z)` vector and crs as this
188
+ * one.
189
+ */
190
+ clone(): Coordinates {
191
+ return new Coordinates(this.crs, this.x, this.y, this.z);
192
+ }
193
+
194
+ /**
195
+ * Copies the `(x, y, z)` vector components and crs of the passed coordinate
196
+ * to this coordinate.
197
+ *
198
+ * @param src - The source coordinate to copy from.
199
+ */
200
+ copy(src: CoordinatesLike): this {
201
+ this.crs = src.crs;
202
+ return this.setFromVector3(src);
203
+ }
204
+
205
+ get longitude() {
206
+ return this.x;
207
+ }
208
+
209
+ get latitude() {
210
+ return this.y;
211
+ }
212
+
213
+ get altitude() {
214
+ return this.z;
215
+ }
216
+
217
+ set altitude(value) {
218
+ this.z = value;
219
+ }
220
+
221
+ /**
222
+ * The geodesic normal of the coordinate.
223
+ */
224
+ get geodesicNormal() {
225
+ if (this._normalNeedsUpdate) {
226
+ this._normalNeedsUpdate = false;
227
+
228
+ if (CRS.is4326(this.crs)) {
229
+ ellipsoid.geodeticSurfaceNormalCartographic(this, this._normal);
230
+ } else if (this.crs == 'EPSG:4978') {
231
+ ellipsoid.geodeticSurfaceNormal(this, this._normal);
232
+ } else {
233
+ this._normal.set(0, 0, 1);
234
+ }
235
+ }
236
+
237
+ return this._normal;
238
+ }
239
+
240
+ /**
241
+ * Copies the `x`, `y` and `z` components into the provided `THREE.Vector3`.
242
+ *
243
+ * @param target - An object to store this vector to. If this is not
244
+ * specified, a new vector will be created.
245
+ *
246
+ * @returns A vector `(x, y, z)`, or copies x, y and z into the provided
247
+ * vector.
248
+ */
249
+ toVector3(target: THREE.Vector3 = new THREE.Vector3()): THREE.Vector3 {
250
+ return target.copy(this);
251
+ }
252
+
253
+ /**
254
+ * Copies the `x`, `y` and `z` components into the provided array.
255
+ *
256
+ * @param array - An array to store this vector to. If this is not
257
+ * provided a new array will be created.
258
+ * @param offset - An optional offset into the array.
259
+ *
260
+ * @returns An array [x, y, z], or copies x, y and z into the provided
261
+ * array.
262
+ */
263
+ toArray(array: number[] = [], offset: number = 0): ArrayLike<number> {
264
+ return THREE.Vector3.prototype.toArray.call(this, array, offset);
265
+ }
266
+
267
+ /**
268
+ * Computes the planar distance from this coordinates to `coord`.
269
+ * **Planar distance** is the straight-line euclidean distance calculated in
270
+ * a 2D cartesian coordinate system.
271
+ */
272
+ planarDistanceTo(coord: Coordinates): number {
273
+ this.toVector3(v0).setZ(0);
274
+ coord.toVector3(v1).setZ(0);
275
+ return v0.distanceTo(v1);
276
+ }
277
+
278
+ /**
279
+ * Computes the geodetic distance from this coordinates to `coord`.
280
+ * **Geodetic distance** is calculated in an ellipsoid space as the shortest
281
+ * distance across the curved surface of the ellipsoid.
282
+ */
283
+ geodeticDistanceTo(coord: Coordinates): number {
284
+ this.as('EPSG:4326', coord0);
285
+ coord.as('EPSG:4326', coord1);
286
+ return ellipsoid.geodesicDistance(coord0, coord1);
287
+ }
288
+
289
+ /**
290
+ * Computes the euclidean distance from this coordinates to `coord` in a
291
+ * WGS84 projection.
292
+ *
293
+ * @param coord - The coordinate
294
+ * @returns earth euclidean distance
295
+ */
296
+ spatialEuclideanDistanceTo(coord: Coordinates): number {
297
+ this.as('EPSG:4978', coord0).toVector3(v0);
298
+ coord.as('EPSG:4978', coord1).toVector3(v1);
299
+ return v0.distanceTo(v1);
300
+ }
301
+
302
+ /**
303
+ * Multiplies this coordinate (with an implicit 1 in the 4th dimension)
304
+ * by `mat`, and divides by perspective.
305
+ *
306
+ * @param mat - The matrix.
307
+ */
308
+ applyMatrix4(mat: THREE.Matrix4): this {
309
+ THREE.Vector3.prototype.applyMatrix4.call(this, mat);
310
+ return this;
311
+ }
312
+
313
+ /**
314
+ * Projects this coordinate to the specified
315
+ * [CRS](http://inspire.ec.europa.eu/theme/rs).
316
+ *
317
+ * @param crs - The target CRS to which the coordinate will be converted.
318
+ * @param target - The target to store the projected coordinate. If this not
319
+ * provided a new coordinate will be created.
320
+ *
321
+ * @returns The coordinate projected into the specified CRS.
322
+ *
323
+ * @example Conversion from a geographic to a geocentric reference system
324
+ * ```js
325
+ * const geographicCoords = new Coordinates('EPSG:4326',
326
+ * 2.33, // longitude
327
+ * 48.24, // latitude
328
+ * 24999549, // altitude
329
+ * );
330
+ * const geocentricCoords = geographicCoords.as('EPSG:4978');
331
+ * ```
332
+ *
333
+ * @example Conversion from a geocentric to a geographic reference system
334
+ * ```js
335
+ * const geocentricCoords = new Coordinates('EPSG:4978',
336
+ * 20885167, // x
337
+ * 849862, // y
338
+ * 23385912, // z
339
+ * );
340
+ * const geographicCoords = geocentricCoords.as('EPSG:4326');
341
+ * ```
342
+ */
343
+ as(crs: ProjectionLike, target = new Coordinates(crs)): Coordinates {
344
+ if (this.crs == crs) {
345
+ target.copy(this);
346
+ } else {
347
+ if (CRS.is4326(this.crs) && crs == 'EPSG:3857') {
348
+ this.y = THREE.MathUtils.clamp(this.y, -89.999999, 89.999999);
349
+ }
350
+
351
+ target.setFromArray(proj4cache(this.crs, crs)
352
+ .forward([this.x, this.y, this.z]));
353
+ }
354
+
355
+ target.crs = crs;
356
+
357
+ return target;
358
+ }
359
+ }
360
+
361
+ coord0 = new Coordinates('EPSG:4326', 0, 0, 0);
362
+ coord1 = new Coordinates('EPSG:4326', 0, 0, 0);
363
+
364
+ export default Coordinates;
package/src/Crs.ts ADDED
@@ -0,0 +1,176 @@
1
+ import proj4 from 'proj4';
2
+
3
+ import type { ProjectionDefinition } from 'proj4';
4
+
5
+ proj4.defs('EPSG:4978', '+proj=geocent +datum=WGS84 +units=m +no_defs');
6
+
7
+ // Redefining proj4 global projections to match epsg.org database axis order.
8
+ // See https://github.com/iTowns/itowns/pull/2465#issuecomment-2517024859
9
+ proj4.defs('EPSG:4326').axis = 'neu';
10
+ proj4.defs('EPSG:4269').axis = 'neu';
11
+ proj4.defs('WGS84').axis = 'neu';
12
+
13
+ /**
14
+ * A projection as a CRS identifier string. This identifier references a
15
+ * projection definition previously defined with
16
+ * [`proj4.defs`](https://github.com/proj4js/proj4js#named-projections).
17
+ */
18
+ export type ProjectionLike = string;
19
+
20
+ function isString(s: unknown): s is string {
21
+ return typeof s === 'string' || s instanceof String;
22
+ }
23
+
24
+ function mustBeString(crs: string) {
25
+ if (!isString(crs)) {
26
+ throw new Error(`Crs parameter value must be a string: '${crs}'`);
27
+ }
28
+ }
29
+
30
+ /**
31
+ * System units supported for a coordinate system. See
32
+ * [proj](https://proj4.org/en/9.5/operations/conversions/unitconvert.html#angular-units).
33
+ * Note that only degree and meters units are supported for now.
34
+ */
35
+ export const UNIT = {
36
+ /**
37
+ * Angular unit in degree.
38
+ */
39
+ DEGREE: 1,
40
+ /**
41
+ * Distance unit in meter.
42
+ */
43
+ METER: 2,
44
+ /**
45
+ * Distance unit in foot.
46
+ */
47
+ FOOT: 3,
48
+ } as const;
49
+
50
+ /**
51
+ * Checks that the CRS is EPSG:4326.
52
+ * @internal
53
+ *
54
+ * @param crs - The CRS to test.
55
+ */
56
+ export function is4326(crs: ProjectionLike) {
57
+ return crs === 'EPSG:4326';
58
+ }
59
+
60
+ function unitFromProj4Unit(proj: ProjectionDefinition) {
61
+ if (proj.units === 'degrees') {
62
+ return UNIT.DEGREE;
63
+ } else if (proj.units === 'm' || proj.units === 'meter') {
64
+ return UNIT.METER;
65
+ } else if (proj.units === 'foot') {
66
+ return UNIT.FOOT;
67
+ } else if (proj.units === undefined && proj.to_meter === undefined) {
68
+ // See https://proj.org/en/9.4/usage/projections.html [17/10/2024]
69
+ // > The default unit for projected coordinates is the meter.
70
+ return UNIT.METER;
71
+ } else {
72
+ return undefined;
73
+ }
74
+ }
75
+
76
+ /**
77
+ * Returns the horizontal coordinates system units associated with this CRS.
78
+ *
79
+ * @param crs - The CRS to extract the unit from.
80
+ * @returns Either `UNIT.METER`, `UNIT.DEGREE`, `UNIT.FOOT` or `undefined`.
81
+ */
82
+ export function getUnit(crs: ProjectionLike) {
83
+ mustBeString(crs);
84
+ const p = proj4.defs(crs);
85
+ if (!p) {
86
+ return undefined;
87
+ }
88
+ return unitFromProj4Unit(p);
89
+ }
90
+
91
+ /**
92
+ * Asserts that the CRS is using metric units.
93
+ *
94
+ * @param crs - The CRS to check.
95
+ * @throws {@link Error} if the CRS is not valid.
96
+ */
97
+ export function isMetricUnit(crs: ProjectionLike) {
98
+ return getUnit(crs) === UNIT.METER;
99
+ }
100
+
101
+ /**
102
+ * Asserts that the CRS is geographic.
103
+ *
104
+ * @param crs - The CRS to check.
105
+ * @throws {@link Error} if the CRS is not valid.
106
+ */
107
+ export function isGeographic(crs: ProjectionLike) {
108
+ return getUnit(crs) === UNIT.DEGREE;
109
+ }
110
+
111
+ /**
112
+ * Asserts that the CRS is geocentric.
113
+ *
114
+ * @param crs - The CRS to test.
115
+ * @returns false if the crs isn't defined.
116
+ */
117
+ export function isGeocentric(crs: ProjectionLike) {
118
+ mustBeString(crs);
119
+ const projection = proj4.defs(crs);
120
+ return !projection ? false : projection.projName == 'geocent';
121
+ }
122
+
123
+ /**
124
+ * Asserts that the CRS is valid, meaning it has been previously defined and
125
+ * includes an unit.
126
+ *
127
+ * @param crs - The CRS to test.
128
+ * @throws {@link Error} if the crs is not valid.
129
+ */
130
+ export function isValid(crs: ProjectionLike) {
131
+ const proj = proj4.defs(crs);
132
+ if (!proj) {
133
+ throw new Error(`Undefined crs '${crs}'. Add it with proj4.defs('${crs}', string)`);
134
+ }
135
+ if (!unitFromProj4Unit(proj)) {
136
+ throw new Error(`No valid unit found for crs '${crs}', found ${proj.units}`);
137
+ }
138
+ }
139
+
140
+ /**
141
+ * Gives a reasonable epsilon for this CRS.
142
+ *
143
+ * @param crs - The CRS to use.
144
+ * @returns 0.01 if the CRS is EPSG:4326, 0.001 otherwise.
145
+ */
146
+ export function reasonableEpsilon(crs: ProjectionLike) {
147
+ if (is4326(crs)) {
148
+ return 0.01;
149
+ } else {
150
+ return 0.001;
151
+ }
152
+ }
153
+
154
+ /**
155
+ * Returns the axis parameter defined in proj4 for the provided crs.
156
+ * Might be undefined depending on crs definition.
157
+ *
158
+ * @param crs - The CRS to get axis from.
159
+ * @returns the matching proj4 axis string, 'enu' for instance (east, north, up)
160
+ */
161
+ export function axisOrder(crs: ProjectionLike) {
162
+ mustBeString(crs);
163
+ const projection = proj4.defs(crs);
164
+ return !projection ? undefined : projection.axis;
165
+ }
166
+
167
+ /**
168
+ * Defines a proj4 projection as a named alias.
169
+ * This function is a specialized wrapper over the
170
+ * [`proj4.defs`](https://github.com/proj4js/proj4js#named-projections)
171
+ * function.
172
+ *
173
+ * @param code - Named alias of the currently defined projection.
174
+ * @param proj4def - Proj4 or WKT string of the defined projection.
175
+ */
176
+ export const defs = (code: string, proj4def: string) => proj4.defs(code, proj4def);