-
Notifications
You must be signed in to change notification settings - Fork 13
/
geo.ts
660 lines (540 loc) · 21.2 KB
/
geo.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
import {
GeoDistanceUnit,
GEO_DISTANCE_UNITS,
GeoPointInput,
GeoShape,
GeoPoint,
GeoDistanceObj,
GeoShapeType,
ESGeoShapeType,
GeoShapePoint,
GeoShapePolygon,
GeoShapeMultiPolygon,
ESGeoShape,
CoordinateTuple,
GeoShapeRelation,
GeoInput
} from '@terascope/types';
import bbox from '@turf/bbox';
import bboxPolygon from '@turf/bbox-polygon';
import equal from '@turf/boolean-equal';
import createCircle from '@turf/circle';
import pointInPolygon from '@turf/boolean-point-in-polygon';
import within from '@turf/boolean-within';
import contains from '@turf/boolean-contains';
import disjoint from '@turf/boolean-disjoint';
import intersect from '@turf/boolean-intersects';
import {
lineString,
multiPolygon,
polygon as tPolygon,
point as tPoint,
MultiPolygon,
Feature,
Properties,
Polygon,
Position,
} from '@turf/helpers';
import lineToPolygon from '@turf/line-to-polygon';
import { getCoords } from '@turf/invariant';
import { find as geoToTimezone, setCache } from 'geo-tz';
import { isArrayLike } from './arrays';
import { isPlainObject, geoHash, getTypeOf } from './deps';
import { trim, toString } from './strings';
import { parseNumberList, toNumber, isNumber } from './numbers';
export const geoJSONTypes = Object.keys(GeoShapeType).map((key) => key.toLowerCase());
// allows for better access and control over tz-geo cache
const TZ_GEO_CACHE = new Map();
export function isGeoJSON(input: unknown): input is GeoShape|ESGeoShape {
if (!isPlainObject(input)) return false;
if (!isArrayLike((input as any).coordinates)) return false;
const type = (input as any).type as unknown;
if (typeof type !== 'string') return false;
return geoJSONTypes.includes(type.toLowerCase());
}
export function isGeoShapePoint(input: unknown): input is GeoShapePoint {
return isGeoJSON(input)
&& (input.type === GeoShapeType.Point || input.type === ESGeoShapeType.Point);
}
export function isGeoShapePolygon(input: unknown): input is GeoShapePolygon {
return isGeoJSON(input)
&& (input.type === GeoShapeType.Polygon || input.type === ESGeoShapeType.Polygon);
}
export function isGeoShapeMultiPolygon(input: unknown): input is GeoShapeMultiPolygon {
return isGeoJSON(input)
&& (input.type === GeoShapeType.MultiPolygon || input.type === ESGeoShapeType.MultiPolygon);
}
export function parseGeoDistance(str: string): GeoDistanceObj {
const matches = trim(str).match(/(\d+)(.*)$/);
if (!matches || !matches.length) {
throw new TypeError(`Incorrect geo distance parameter provided: ${str}`);
}
const distance = Number(matches[1]);
const unit = parseGeoDistanceUnit(matches[2]);
return { distance, unit };
}
export function parseGeoDistanceUnit(input: string): GeoDistanceUnit {
const unit = GEO_DISTANCE_UNITS[trim(input)];
if (!unit) {
throw new TypeError(`Incorrect distance unit provided: ${input}`);
}
return unit;
}
function getLonAndLat(input: unknown, throwInvalid = true): GeoPoint | null {
if (!isPlainObject(input)) {
if (!throwInvalid) return null;
throw new TypeError(`Invalid geo point, expected object, got ${input} (${getTypeOf(input)})`);
}
const obj = input as Record<string, unknown>;
let lat: unknown;
let lon: unknown;
if ('lat' in obj && 'lon' in obj) {
if (isNumber(obj.lat) && isNumber(obj.lon)) {
return obj as unknown as GeoPoint;
}
lat = obj.lat;
lon = obj.lon;
} else if ('latitude' in obj && 'longitude' in obj) {
lat = obj.latitude;
lon = obj.longitude;
} else if (isGeoShapePoint(obj)) {
[lon, lat] = obj.coordinates;
}
if (throwInvalid && (lat == null || lon == null)) {
if (isGeoShapePolygon(obj) || isGeoShapeMultiPolygon(obj)) {
throw new TypeError([
`Expected a Point geo shape, received a geo ${obj.type} shape,`,
'you may need to switch to a polygon compatible operation'
].join(' '));
}
throw new TypeError('Invalid geo point object, it must contain keys lat,lon or latitude/longitude');
}
lat = toNumber(lat);
lon = toNumber(lon);
if (!isNumber(lat) || !isNumber(lon)) {
if (throwInvalid) {
throw new TypeError('Invalid geo point, lat and lon must be numbers');
}
return null;
}
return { lat, lon };
}
/**
* Convert an input into a Geo Point object with lat and lon
*/
export function parseGeoPoint(point: GeoPointInput|unknown): GeoPoint;
export function parseGeoPoint(point: GeoPointInput|unknown, throwInvalid: true): GeoPoint;
export function parseGeoPoint(point: GeoPointInput|unknown, throwInvalid: false): GeoPoint | null;
export function parseGeoPoint(point: GeoPointInput|unknown, throwInvalid = true): GeoPoint | null {
let lat: number | undefined;
let lon: number | undefined;
if (typeof point === 'string') {
if (point.includes(',')) {
[lat, lon] = parseNumberList(point);
} else {
try {
return geoHash.decode(point);
} catch (err) {
// do nothing
}
}
} else if (isPlainObject(point)) {
const results = getLonAndLat(point, throwInvalid);
if (results) return results;
} else if (isArrayLike(point)) {
// array of points are meant to be lon/lat format
[lon, lat] = parseNumberList(point);
}
if (throwInvalid && (lat == null || lon == null)) {
throw new TypeError(`Invalid geo point given to parse, got ${point} (${getTypeOf(point)})`);
}
// data incoming is lat,lon and we must return lon,lat
if (lat != null && lon != null) {
return {
lat,
lon
};
}
return null;
}
export function isGeoPoint(input: unknown): boolean {
return parseGeoPoint(input as GeoPointInput, false) != null;
}
export function makeGeoBBox(point1: GeoPoint, point2: GeoPoint): Feature<Polygon, Properties> {
const line = lineString([
makeCoordinatesFromGeoPoint(point1),
makeCoordinatesFromGeoPoint(point2)
]);
const box = bbox(line);
return bboxPolygon(box);
}
export function inGeoBoundingBox(
top_left: GeoPointInput, bottom_right: GeoPointInput, point: GeoPointInput
): boolean {
const topLeft = parseGeoPoint(top_left);
const bottomRight = parseGeoPoint(bottom_right);
const polygon = makeGeoBBox(topLeft, bottomRight);
if (polygon == null) {
throw new Error(`Invalid bounding box created from topLeft: ${topLeft}, bottomRight: ${bottomRight}`);
}
return geoPolyHasPoint(polygon)(point);
}
export function inGeoBoundingBoxFP(
top_left: GeoPointInput, bottom_right: GeoPointInput
): (input: unknown) => boolean {
const topLeft = parseGeoPoint(top_left);
const bottomRight = parseGeoPoint(bottom_right);
const polygon = makeGeoBBox(topLeft, bottomRight);
if (polygon == null) {
throw new Error(`Invalid bounding box created from topLeft: ${topLeft}, bottomRight: ${bottomRight}`);
}
return geoPolyHasPoint(polygon);
}
export function makeCoordinatesFromGeoPoint(point: GeoPoint): CoordinateTuple {
return [point.lon, point.lat];
}
export function geoPolyHasPoint<G extends Polygon | MultiPolygon>(polygon: Feature<G>|G) {
return (fieldData: unknown): boolean => {
const point = parseGeoPoint(fieldData as any, false);
if (!point) return false;
return pointInPolygon(makeCoordinatesFromGeoPoint(point), polygon);
};
}
export function makeGeoCircle(
point: GeoPoint, distance: number, unitVal?: GeoDistanceUnit
): Feature<Polygon>|undefined {
// There is a mismatch between elasticsearch and turf on "inch" naming
const units = unitVal === 'inch' ? 'inches' : unitVal;
return createCircle(makeCoordinatesFromGeoPoint(point), distance, { units });
}
export function geoPointWithinRange(
startingPoint: GeoPointInput, distanceValue: string, point: GeoPointInput
): boolean {
const sPoint = parseGeoPoint(startingPoint);
const { distance, unit } = parseGeoDistance(distanceValue);
const polygon = makeGeoCircle(sPoint, distance, unit);
if (polygon == null) {
throw new Error(`Invalid startingPoint: ${startingPoint}`);
}
return geoPolyHasPoint(polygon)(point);
}
export function geoPointWithinRangeFP(
startingPoint: GeoPointInput, distanceValue: string
): (input: unknown) => boolean {
const sPoint = parseGeoPoint(startingPoint);
const { distance, unit } = parseGeoDistance(distanceValue);
const polygon = makeGeoCircle(sPoint, distance, unit);
if (polygon == null) {
throw new Error(`Invalid startingPoint: ${startingPoint}`);
}
return geoPolyHasPoint(polygon);
}
export function geoRelationFP(
geoShape: GeoInput, relation: GeoShapeRelation
): (input: unknown) => boolean {
if (relation === GeoShapeRelation.Within) {
return geoWithinFP(geoShape);
}
if (relation === GeoShapeRelation.Contains) {
return geoContainsFP(geoShape);
}
if (relation === GeoShapeRelation.Intersects) {
return geoIntersectsFP(geoShape);
}
if (relation === GeoShapeRelation.Disjoint) {
return geoDisjointFP(geoShape);
}
throw new Error(`Unsupported relation ${relation}`);
}
/** Converts a geoJSON object to its turf geo feature counterpart */
export function makeGeoFeature(geoShape: unknown): Feature<any>|undefined {
if (isGeoShapePoint(geoShape)) {
return tPoint(geoShape.coordinates);
}
if (isGeoShapeMultiPolygon(geoShape)) {
return multiPolygon(geoShape.coordinates);
}
if (isGeoShapePolygon(geoShape)) {
return tPolygon(geoShape.coordinates);
}
return;
}
/** Converts a geoJSON object to its turf geo feature counterpart, will throw if not valid */
export function makeGeoFeatureOrThrow(geoShape: unknown): Feature<any> {
const results = makeGeoFeature(geoShape);
if (!results) {
throw new Error(`Invalid input: ${JSON.stringify(geoShape)}, is not a valid geo-shape`);
}
return results;
}
/**
* Returns true if the second geometry is completely contained by the first geometry.
* The interiors of both geometries must intersect and, the interior and boundary of
* the secondary geometry must not intersect the exterior of the first geometry.
*/
export function geoContains(firstGeoEntity: GeoInput, secondGeoEntity: GeoInput): boolean {
return geoContainsFP(secondGeoEntity)(firstGeoEntity);
}
/**
* When provided with geoInput that acts as the argument geo-feature, it will return a function
* that accepts any geoInput and checks to see if the new input contains the argument geo-feature
*/
export function geoContainsFP(queryGeoEntity: GeoInput): (input: unknown) => boolean {
const queryGeo = toGeoJSONOrThrow(queryGeoEntity);
const queryFeature = makeGeoFeatureOrThrow(queryGeo);
if (isGeoShapePoint(queryGeo)) return _pointContains(queryFeature);
const {
polygons: queryPolygons,
holes: queryHoles
} = _featureToPolygonAndHoles(queryFeature);
return function _geoContains(input: unknown): boolean {
const inputGeoEntity = toGeoJSON(input);
if (!inputGeoEntity) return false;
if (isGeoPoint(inputGeoEntity)) {
// point cannot contain a poly like feature
return false;
}
const inputFeature = makeGeoFeature(inputGeoEntity);
if (!inputFeature) return false;
const {
polygons: inputPolygons,
holes: inputHoles
} = _featureToPolygonAndHoles(inputFeature);
if (inputHoles.length) {
const withinInputHole = inputHoles.some(
(iHolePoly) => queryPolygons.some((qPoly) => intersect(qPoly, iHolePoly))
);
if (withinInputHole) {
// check to see if holes are the same, if so they don't overlap
if (queryHoles.length) {
return queryHoles.some(
(qHole) => inputHoles.some((iHole) => equal(qHole, iHole))
);
}
return false;
}
}
return queryPolygons.every(
(qPoly) => inputPolygons.some((iPoly) => contains(iPoly, qPoly))
);
};
}
function _pointContains(queryFeature: Feature<any>) {
return (input: unknown) => {
const inputGeoEntity = toGeoJSON(input);
if (!inputGeoEntity) return false;
const inputFeature = makeGeoFeature(inputGeoEntity);
if (!inputFeature) return false;
if (isGeoPoint(inputGeoEntity)) {
return equal(inputFeature, queryFeature);
}
const {
polygons,
holes
} = _featureToPolygonAndHoles(inputFeature);
let pointInHole = false;
if (holes.length) {
pointInHole = holes.some((iPolyHole) => contains(iPolyHole, queryFeature));
}
return !pointInHole && polygons.some((poly) => contains(poly, queryFeature));
};
}
function _featureToPolygonAndHoles(inputFeature: Feature<any>) {
const inputHoles: Feature<any>[] = [];
const inputCoords = getCoords(inputFeature);
let inputPolygons: Feature<any>[];
if (inputFeature.geometry.type === 'MultiPolygon') {
inputPolygons = inputCoords
.map((coords) => {
if (coords.length > 1) {
const [polygon, ...holes] = coords.map(
(innerCords: Position[]) => tPolygon([innerCords])
);
inputHoles.push(...holes);
return polygon;
}
return tPolygon(coords);
}) as Feature<any>[];
} else if (inputFeature.geometry.type === 'Polygon') {
const [polyCoords, ...holeCords] = inputCoords;
inputPolygons = [tPolygon([polyCoords])];
const holePolygons = holeCords.map((coords) => tPolygon([coords])) as Feature<any>[];
inputHoles.push(...holePolygons);
} else {
throw new Error(`Cannot convert ${toString(inputFeature)} to a polygon`);
}
return { holes: inputHoles, polygons: inputPolygons };
}
function _pointToPointMatch(queryInput: Feature<any>) {
return (input: unknown) => {
const inputGeoEntity = toGeoJSON(input);
if (!inputGeoEntity) return false;
if (!isGeoShapePoint(inputGeoEntity)) return false;
const inputFeature = makeGeoFeature(inputGeoEntity);
if (!inputFeature) return false;
return equal(queryInput, inputFeature);
};
}
/**
* Returns true if the first geometry is completely within the second geometry.
* The interiors of both geometries must intersect and, the interior and boundary
* of the first geometry must not intersect the exterior of the second geometry
*/
export function geoWithin(firstGeoEntity: GeoInput, secondGeoEntity: GeoInput): boolean {
return geoWithinFP(secondGeoEntity)(firstGeoEntity);
}
/**
* When provided with geoInput that acts as the parent geo-feature, it will return a function
* that accepts any geoInput and checks to see if the new input is within the parent geo-feature
*/
export function geoWithinFP(queryGeoEntity: GeoInput): (input: unknown) => boolean {
const queryGeo = toGeoJSONOrThrow(queryGeoEntity);
const queryFeature = makeGeoFeatureOrThrow(queryGeo);
// point can only be compared to other points
if (isGeoShapePoint(queryGeo)) return _pointToPointMatch(queryFeature);
const { polygons: queryPolygons, holes: queryHoles } = _featureToPolygonAndHoles(queryFeature);
const hasQueryHoles = queryHoles.length > 0;
return function _geoWithinFP(input) {
const inputGeoEntity = toGeoJSON(input);
if (!inputGeoEntity) return false;
const inputFeature = makeGeoFeature(inputGeoEntity);
if (!inputFeature) return false;
if (isGeoShapePoint(inputGeoEntity)) {
if (hasQueryHoles) {
const withinQueryHole = queryHoles.some(
intersect.bind(intersect, inputFeature)
);
if (withinQueryHole) return false;
}
return queryPolygons.some(within.bind(within, inputFeature));
}
const {
polygons: inputPolygons,
holes: inputHoles
} = _featureToPolygonAndHoles(inputFeature);
if (hasQueryHoles) {
// holes intersect main body
const withinQueryHole = queryHoles.some(
(qHole) => {
const bool = intersect(inputFeature, qHole);
if (bool && inputHoles.length) {
// if they are equal, then don't immediately falsify
const inner = !inputHoles.some(equal.bind(equal, qHole));
return inner;
}
return bool;
}
);
if (withinQueryHole) return false;
}
return inputPolygons.every(
(iPoly) => queryPolygons.some(within.bind(within, iPoly))
);
};
}
/** Returns true if both geo entities intersect each other, if one of the input geo entity
* is a point, it will check if the other geo-entity contains the point
*/
export function geoIntersects(firstGeoEntity: GeoInput, secondGeoEntity: GeoInput):boolean {
return geoIntersectsFP(firstGeoEntity)(secondGeoEntity);
}
export function geoIntersectsFP(queryGeoEntity: GeoInput): (input: unknown) => boolean {
const queryGeo = toGeoJSONOrThrow(queryGeoEntity);
const queryFeature = makeGeoFeatureOrThrow(queryGeo);
return function _geoIntersectsFP(input: unknown) {
const inputGeoEntity = toGeoJSON(input);
if (!inputGeoEntity) return false;
const inputFeature = makeGeoFeature(inputGeoEntity);
if (!inputFeature) return false;
return intersect(inputFeature, queryFeature);
};
}
export function geoDisjointFP(queryGeoEntity: GeoInput): (input: unknown) => boolean {
const queryGeo = toGeoJSONOrThrow(queryGeoEntity);
const queryFeature = makeGeoFeatureOrThrow(queryGeo);
return function _geoDisjointFP(input: unknown) {
const inputGeoEntity = toGeoJSON(input);
if (!inputGeoEntity) return false;
const inputFeature = makeGeoFeature(inputGeoEntity);
if (!inputFeature) return false;
return disjoint(inputFeature, queryFeature);
};
}
/** Returns true if both geo entities have no overlap */
export function geoDisjoint(firstGeoEntity: GeoInput, secondGeoEntity: GeoInput):boolean {
return geoDisjointFP(firstGeoEntity)(secondGeoEntity);
}
const esTypeMap = {
[ESGeoShapeType.Point]: GeoShapeType.Point,
[ESGeoShapeType.MultiPolygon]: GeoShapeType.MultiPolygon,
[ESGeoShapeType.Polygon]: GeoShapeType.Polygon,
} as const;
/** Only able to convert geo-points to either a geo-json point or a simple polygon.
* There is no current support for creating polygon with holes or multi-polygon
* as of right now. geoJSON input is made sure to be properly formatted for its type value
*/
export function toGeoJSON(input: unknown): GeoShape|undefined {
if (isGeoJSON(input)) {
const { type: inputType } = input;
const type = esTypeMap[inputType] ? esTypeMap[inputType] : inputType;
return { ...input, type };
}
if (isGeoPoint(input)) {
const coordinates = makeCoordinatesFromGeoPoint(parseGeoPoint(input as GeoPointInput));
return {
type: GeoShapeType.Point,
coordinates
};
}
if (Array.isArray(input)) {
try {
const points = input.map((point) => makeCoordinatesFromGeoPoint(
parseGeoPoint(point as GeoPointInput)
));
const coordinates = validateListCoords(points);
return {
type: GeoShapeType.Polygon,
coordinates
};
} catch (_err) {
// ignore here
}
}
}
export function toGeoJSONOrThrow(input: unknown): GeoShape {
const geoJSON = toGeoJSON(input);
if (!geoJSON) {
throw new Error(`Cannot convert ${JSON.stringify(input)} to valid geoJSON`);
}
return geoJSON;
}
export function validateListCoords(coords: CoordinateTuple[]): any[] {
if (coords.length < 3) {
throw new Error('Points parameter for a geoPolygon query must have at least three geo-points');
}
const line = lineString(coords);
const polygon = lineToPolygon(line);
// @ts-expect-error
return getCoords(polygon);
}
export function polyHasHoles(input: GeoShape): boolean {
if (isGeoShapePolygon(input)) {
return input.coordinates.length > 1;
}
if (isGeoShapeMultiPolygon(input)) {
return input.coordinates[0].length > 1;
}
return false;
}
/** Takes in a geo point like entity and returns the timezone of its location */
export function lookupTimezone(input: unknown): string {
if (!tzCacheLoaded()) {
setCache({ preload: true, store: TZ_GEO_CACHE });
}
const { lat, lon } = parseGeoPoint(input as GeoPointInput);
// it returns an array, return the first one
return geoToTimezone(lat, lon)[0];
}
export function tzCacheLoaded(): boolean {
return TZ_GEO_CACHE.size > 0;
}