forked from sharedstreets/sharedstreets-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
757 lines (706 loc) · 25.2 KB
/
index.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
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
import bearing from "@turf/bearing";
import { bearingToAzimuth, Feature, lineString, LineString, Point, Position } from "@turf/helpers";
import { getCoord } from "@turf/invariant";
import length from "@turf/length";
import lineOffset from "@turf/line-offset";
import BigNumber from "bignumber.js";
import { createHash } from "crypto";
import {
FormOfWay, GISMetadata, LocationReference, OSMMetadata,
SharedStreetsGeometry, SharedStreetsIntersection, SharedStreetsMetadata, SharedStreetsReference,
} from "sharedstreets-types";
import { isArray } from "util";
/**
* Shared Streets Java implementation
*
* @private
* Intersection
* https://github.com/sharedstreets/sharedstreets-builder/blob/master/src/main/java/io/sharedstreets/data/SharedStreetsIntersection.java#L42-L49
*
* Geometry
* https://github.com/sharedstreets/sharedstreets-builder/blob/master/src/main/java/io/sharedstreets/data/SharedStreetsGeometry.java#L98-L108
*
* Reference
* https://github.com/sharedstreets/sharedstreets-builder/blob/master/src/main/java/io/sharedstreets/data/SharedStreetsReference.java#L323-L340
*
* Location Reference
* https://github.com/sharedstreets/sharedstreets-builder/blob/master/src/main/java/io/sharedstreets/data/SharedStreetsLocationReference.java
*
* OpenLR White Paper
* http://www.openlr.org/data/docs/OpenLR-Whitepaper_v1.5.pdf
*/
/**
* Geometry Id
*
* @param {Feature<LineString>|Array<Array<number>>} line Line Geometry as a GeoJSON LineString or an Array of Positions Array<<longitude, latitude>>.
* @returns {string} SharedStreets Geometry Id
* @example
* const id = sharedstreets.geometryId([[110, 45], [115, 50], [120, 55]]);
* id // => "ce9c0ec1472c0a8bab3190ab075e9b21"
*/
export function geometryId(line: Feature<LineString> | LineString | number[][]): string {
const message = geometryMessage(line);
return generateHash(message);
}
/**
* Geometry Message
*
* @private
*/
export function geometryMessage(line: Feature<LineString> | LineString | number[][]): string {
const coords = getCoords(line);
return "Geometry " + coords.map(([x, y]) => `${round(x)} ${round(y)}`).join(" ");
}
/**
* geometry
*
* @param {Feature<LineString>|Array<Array<number>>} line GeoJSON LineString Feature
* @param {Object} [options={}] Optional parameters
* @param {string} [options.formOfWay] Property field that contains FormOfWay value (number/string).
* @param {string} [options.roadClass] Property field that contains RoadClass value (number/string).
* @returns {SharedStreetsGeometry} SharedStreets Geometry
* @example
* const line = [[110, 45], [115, 50], [120, 55]];
* const geom = sharedstreets.geometry(line);
* geom.id; // => "ce9c0ec1472c0a8bab3190ab075e9b21"
* geom.lonlats; // => [ 110, 45, 115, 50, 120, 55 ]
*/
export function geometry(line: Feature<LineString> | LineString | number[][], options: {
formOfWay?: string,
roadClass?: string,
// To-Do
// - fromIntersection [optional]
// - toIntersection [optional]
// - forwardReference [optional]
// - backReference [optional]
} = {}): SharedStreetsGeometry {
let properties: any = {};
const coords = getCoords(line);
// Extract Properties from GeoJSON LineString Feature
if (!isArray(line) && line.type === "Feature") { properties = line.properties || {}; }
// Attributes for Forward & Back References
const start = coords[0];
const end = coords[coords.length - 1];
const distToNextRef = distanceToNextRef(line);
const outBearing = outboundBearing(line);
const inBearing = inboundBearing(line);
// FormOfWay needs to be extracted from the GeoJSON properties.
let formOfWay = 0;
if (options.formOfWay && properties[options.formOfWay]) {
formOfWay = properties[options.formOfWay];
}
// RoadClass needs to be extracted from the GeoJSON properties.
let roadClass = "Other";
if (options.roadClass && properties[options.roadClass]) {
roadClass = properties[options.roadClass];
}
// To-Do make below from Optional parameters
// Location References
const fromIntersection = locationReference(start, {
distanceToNextRef: distToNextRef,
outboundBearing: outBearing,
});
const toIntersection = locationReference(end, {
inboundBearing: inBearing,
});
const fromIntersectionId = fromIntersection.intersectionId;
const toIntersectionId = toIntersection.intersectionId;
// Forward/Back Reference
const forwardReferenceId = referenceId([fromIntersection, toIntersection], formOfWay);
const backReferenceId = referenceId([toIntersection, fromIntersection], formOfWay);
// Save Results
const id = geometryId(line);
const lonlats = coordsToLonlats(coords);
return {
id,
fromIntersectionId,
toIntersectionId,
forwardReferenceId,
backReferenceId,
roadClass,
lonlats,
};
}
/**
* Intersection Id
*
* @param {Feature<Point>|Array<number>} pt Point location reference as a GeoJSON Point or an Array of numbers <longitude, latitude>.
* @returns {string} SharedStreets Intersection Id
* @example
* const id = sharedstreets.intersectionId([110, 45]);
* id // => "71f34691f182a467137b3d37265cb3b6"
*/
export function intersectionId(pt: number[] | Feature<Point> | Point): string {
const message = intersectionMessage(pt);
return generateHash(message);
}
/**
* Intersection Message
*
* @private
*/
export function intersectionMessage(pt: number[] | Feature<Point> | Point): string {
const [lon, lat] = getCoord(pt);
return `Intersection ${round(lon)} ${round(lat)}`;
}
/**
* Intersection
*
* @param {Feature<Point>|Array<number>} pt Point location reference as a GeoJSON Point or an Array of numbers <longitude, latitude>.
* @param {Object} [options={}] Optional parameters
* @param {string} [options.nodeId] Define NodeId for Intersection
* @returns {SharedStreetsIntersection} SharedStreets Intersection
* @example
* const intersection = sharedstreets.intersection([110, 45]);
* intersection.id // => "71f34691f182a467137b3d37265cb3b6"
*/
export function intersection(pt: number[] | Feature<Point> | Point, options: {
nodeId?: number,
inboundReferences?: LocationReference[],
outboundReferencesIds?: LocationReference[],
} = {}): SharedStreetsIntersection {
// Default params
const inboundReferences = options.inboundReferences || [];
const outboundReferences = options.outboundReferencesIds || [];
const nodeId = options.nodeId;
// Main
const [lon, lat] = getCoord(pt);
const id = intersectionId(pt);
const inboundReferenceIds = inboundReferences.map((ref) => ref.intersectionId);
const outboundReferenceIds = outboundReferences.map((ref) => ref.intersectionId);
const data: SharedStreetsIntersection = {
id,
lon,
lat,
inboundReferenceIds,
outboundReferenceIds,
};
if (nodeId !== undefined) { data.nodeId = nodeId; }
return data;
}
/**
* Reference Id
*
* @param {Array<LocationReference>} locationReferences An Array of Location References.
* @param {FormOfWay} [formOfWay=0] Form Of Way
* @returns {string} SharedStreets Reference Id
* @example
* const locationReferences = [
* sharedstreets.locationReference([-74.0048213, 40.7416415], {outboundBearing: 208, distanceToNextRef: 9279}),
* sharedstreets.locationReference([-74.0051265, 40.7408505], {inboundBearing: 188})
* ];
* const formOfWay = 2; // => "MultipleCarriageway"
*
* const id = sharedstreets.referenceId(locationReferences, formOfWay);
* id // => "ef209661aeebadfb4e0a2cb93153493f"
*/
export function referenceId(
locationReferences: LocationReference[],
formOfWay = FormOfWay.Undefined,
): string {
const message = referenceMessage(locationReferences, formOfWay);
return generateHash(message);
}
/**
* Reference Message
*
* @private
*/
export function referenceMessage(
locationReferences: LocationReference[],
formOfWay = FormOfWay.Undefined,
): string {
// Convert FormOfWay to Number if encoding ID
if (typeof formOfWay !== "number") { formOfWay = getFormOfWayNumber(formOfWay); }
let message = `Reference ${formOfWay}`;
locationReferences.forEach((lr) => {
message += ` ${round(lr.lon)} ${round(lr.lat)}`;
if (lr.outboundBearing !== null && lr.outboundBearing !== undefined &&
lr.distanceToNextRef !== null && lr.distanceToNextRef !== undefined) {
message += ` ${Math.floor(lr.outboundBearing)}`;
message += ` ${Math.floor(lr.distanceToNextRef)}`; // distanceToNextRef must be stored in centimeter
}
});
return message;
}
/**
* Reference
*
* @param {SharedStreetsGeometry} geom SharedStreets Geometry
* @param {Array<LocationReference>} locationReferences An Array of Location References.
* @param {number} [formOfWay=0] Form Of Way (default Undefined)
* @returns {SharedStreetsReference} SharedStreets Reference
* @example
* const line = [[110, 45], [115, 50], [120, 55]];
* const geom = sharedstreets.geometry(line);
* const locationReferences = [
* sharedstreets.locationReference([-74.0048213, 40.7416415], {outboundBearing: 208, distanceToNextRef: 9279}),
* sharedstreets.locationReference([-74.0051265, 40.7408505], {inboundBearing: 188}),
* ];
* const formOfWay = 2; // => "MultipleCarriageway"
* const ref = sharedstreets.reference(geom, locationReferences, formOfWay);
* ref.id // => "ef209661aeebadfb4e0a2cb93153493f"
*/
export function reference(
geom: SharedStreetsGeometry,
locationReferences: LocationReference[],
formOfWay = FormOfWay.Undefined,
): SharedStreetsReference {
return {
id: referenceId(locationReferences, formOfWay),
geometryId: geom.id,
formOfWay,
locationReferences,
};
}
/**
* Forward Reference
*
* @param {Feature<LineString>|Array<Array<number>>} line GeoJSON LineString Feature or an Array of Positions
* @param {Object} [options={}] Optional parameters
* @param {number|string} [options.formOfWay=0] Form of Way (default "Undefined")
* @returns {SharedStreetsReference} Forward SharedStreets Reference
* @example
* const line = [[110, 45], [115, 50], [120, 55]];
* const ref = sharedstreets.forwardReference(line);
* ref.id // => "3f652e4585aa7d7df3c1fbe4f55cea0a"
*/
export function forwardReference(
line: Feature<LineString> | LineString | Position[],
options: {
formOfWay?: number|string,
} = {},
): SharedStreetsReference {
const start = getStartCoord(line);
const end = getEndCoord(line);
const formOfWay = getFormOfWay(line, options);
const geomId = geometryId(line);
const outBearing = outboundBearing(line);
const inBearing = inboundBearing(line);
const distToNextRef = distanceToNextRef(line);
const locationReferences = [
locationReference(start, {outboundBearing: outBearing, distanceToNextRef: distToNextRef}),
locationReference(end, {inboundBearing: inBearing}),
];
const id = referenceId(locationReferences, formOfWay);
return {
id,
geometryId: geomId,
formOfWay,
locationReferences,
};
}
/**
* Back Reference
*
* @param {Feature<LineString>|Array<Array<number>>} line GeoJSON LineString Feature or an Array of Positions
* @param {Object} [options={}] Optional parameters
* @param {number|string} [options.formOfWay=0] Form of Way (default "Undefined")
* @returns {SharedStreetsReference} Back SharedStreets Reference
* @example
* const line = [[110, 45], [115, 50], [120, 55]];
* const ref = sharedstreets.backReference(line);
* ref.id // => "a18b2674e41cad630f5693154837baf4"
*/
export function backReference(
line: Feature<LineString> | LineString | Position[],
options: {
formOfWay?: number|string,
} = {},
): SharedStreetsReference {
// Back Reference switches Start => End
const end = getStartCoord(line);
const start = getEndCoord(line);
const formOfWay = getFormOfWay(line, options);
const geomId = geometryId(line);
const outBearing = outboundBearing(line);
const inBearing = inboundBearing(line);
const distToNextRef = distanceToNextRef(line);
const locationReferences = [
locationReference(start, {outboundBearing: outBearing, distanceToNextRef: distToNextRef}),
locationReference(end, {inboundBearing: inBearing}),
];
const id = referenceId(locationReferences, formOfWay);
return {
id,
geometryId: geomId,
formOfWay,
locationReferences,
};
}
/**
* Location Reference
*
* @private
* @param {Feature<Point>|Array<number>} pt Point as a GeoJSON Point or an Array of numbers <longitude, latitude>.
* @param {Object} [options={}] Optional parameters
* @param {string} [options.intersectionId] Intersection Id - Fallbacks to input's point `id` or generates Intersection Id.
* @param {number} [options.inboundBearing] Inbound bearing of the street geometry for the 20 meters immediately following the location reference.
* @param {number} [options.outboundBearing] Outbound bearing.
* @param {number} [options.distanceToNextRef] Distance to next Location Reference (distance must be defined in centimeters).
* @returns {LocationReference} SharedStreets Location Reference
* @example
* const options = {
* outboundBearing: 208,
* distanceToNextRef: 9279
* };
* const locRef = sharedstreets.locationReference([-74.00482177734375, 40.741641998291016], options);
* locRef.intersectionId // => "5c88d4fa3900a083355c46c54da8f584"
*/
export function locationReference(
pt: number[] | Feature<Point> | Point,
options: {
intersectionId?: string,
inboundBearing?: number,
outboundBearing?: number,
distanceToNextRef?: number,
} = {}): LocationReference {
const coord = getCoord(pt);
const id = options.intersectionId || intersectionId(coord);
// Include extra properties & Reference ID to GeoJSON Properties
const locRef: LocationReference = {
intersectionId: id,
lat: coord[1],
lon: coord[0],
};
if (options.inboundBearing !== undefined) { locRef.inboundBearing = options.inboundBearing; }
if (options.outboundBearing !== undefined) { locRef.outboundBearing = options.outboundBearing; }
if (options.distanceToNextRef !== undefined) { locRef.distanceToNextRef = options.distanceToNextRef; }
if (locRef.outboundBearing !== undefined && locRef.distanceToNextRef === undefined) {
throw new Error("distanceToNextRef is required if outboundBearing is present");
}
return locRef;
}
/**
* Metadata
*
* @param {SharedStreetsGeometry} geom SharedStreets Geometry
* @param {OSMMetadata} [osmMetadata={}] OSM Metadata
* @param {Array<GISMetadata>} [gisMetadata=[]] GIS Metadata
* @param {}
* @returns {SharedStreetsMetadata} SharedStreets Metadata
* @example
* const line = [[110, 45], [115, 50], [120, 55]];
* const geom = sharedstreets.geometry(line);
* const metadata = sharedstreets.metadata(geom)
*/
export function metadata(
geom: SharedStreetsGeometry,
osmMetadata: OSMMetadata = {},
gisMetadata: GISMetadata[] = [],
): SharedStreetsMetadata {
return {
geometryId: geom.id,
osmMetadata,
gisMetadata,
};
}
/**
* Calculates outbound bearing from a LineString
*
* @param {Feature<LineString>|Array<Array<number>>} line GeoJSON LineString or an Array of Positions
* @returns {number} Outbound Bearing
* @example
* const line = [[110, 45], [115, 50], [120, 55]];
* const outboundBearing = sharedstreets.outboundBearing(line);
* outboundBearing; // => 208
*/
export function outboundBearing(line: Feature<LineString>|LineString|number[][]): number {
const coords = getCoords(line);
// Calculate Distances
const start = coords[0];
// LRs describe the compass bearing of the street geometry for the 20 meters immediately following the LR.
const line20m = lineOffset(lineString(coords), 20, {units: "meters"});
const line20mCoords = getCoords(line20m);
const start20m = line20mCoords[line20mCoords.length - 1];
// Calculate outbound & inbound
return bearingToAzimuth(Math.floor(bearing(start, start20m)));
}
/**
* Calculates inbound bearing from a LineString
*
* @param {Feature<LineString>|Array<Array<number>>} line GeoJSON LineString or an Array of Positions
* @returns {number} Inbound Bearing
* @example
* const line = [[110, 45], [115, 50], [120, 55]];
* const inboundBearing = sharedstreets.inboundBearing(line);
* inboundBearing; // => 188
*/
export function inboundBearing(line: Feature<LineString>|LineString|Position[]): number {
const coords = getCoords(line);
const start = coords[0];
const end = coords[coords.length - 1];
return bearingToAzimuth(Math.floor(bearing(end, start)));
}
/**
* Calculates inbound bearing from a LineString
*
* @param {Coord} start GeoJSON Point or an Array of numbers [Longitude/Latitude]
* @param {Coord} end GeoJSON Point or an Array of numbers [Longitude/Latitude]
* @returns {number} Distance to next Ref in centimeters
* @example
* const start = [110, 45];
* const end = [120, 55];
* const distanceToNextRef = sharedstreets.distanceToNextRef(start, end);
* distanceToNextRef; // => 9279
*/
export function distanceToNextRef(line: Feature<LineString>|LineString|Position[]): number {
if (Array.isArray(line)) { line = lineString(line); }
return Math.floor(length(line, {units: "meters"}) * 100);
}
/**
* Converts lonlats to GeoJSON LineString Coords
*
* @param {Array<number>} lonlats Single Array of paired longitudes & latitude
* @returns {Array<Array<number>>} GeoJSON LineString coordinates
* @example
* const coords = lonlatsToCoords([110, 45, 120, 55]);
* coords // => [[110, 45], [120, 55]]
*/
export function lonlatsToCoords(lonlats: number[]) {
const coords: number[][] = [];
lonlats.reduce((lon, deg, index) => {
if (index % 2 === 0) { return deg; } // Longitude
coords.push([lon, deg]);
return deg; // Latitude
});
return coords;
}
/**
* Converts GeoJSON LineString Coords to lonlats
*
* @param {Array<Array<number, number>>} coords GeoJSON LineString coordinates
* @returns {Array<number>} lonlats Single Array of paired longitudes & latitude
* @example
* const lonlats = coordsToLonlats([[110, 45], [120, 55]]);
* lonlats // => [110, 45, 120, 55]
*/
export function coordsToLonlats(coords: number[][]) {
const lonlats: number[] = [];
coords.forEach((coord) => {
lonlats.push(coord[0], coord[1]);
});
return lonlats;
}
/**
* Generates Base16 Hash
*
* @param {string} message Message to hash
* @returns {string} SharedStreets Reference ID
* @example
* const message = "Intersection -74.00482177734375 40.741641998291016";
* const hash = sharedstreets.generateHash(message);
* hash // => "69f13f881649cb21ee3b359730790bb9"
*/
export function generateHash(message: string): string {
return createHash("md5").update(message).digest("hex");
}
/**
* Get RoadClass from a Number to a String
*
* @param {number} value Number value [between 0-8]
* @returns {string} Road Class
* @example
* sharedstreets.getRoadClassString(0); // => "Motorway"
* sharedstreets.getRoadClassString(5); // => "Residential"
*/
export function getRoadClassString(value: number) {
switch (value) {
case 0: return "Motorway";
case 1: return "Trunk";
case 2: return "Primary";
case 3: return "Secondary";
case 4: return "Tertiary";
case 5: return "Residential";
case 6: return "Unclassified";
case 7: return "Service";
case 8: return "Other";
default: throw new Error(`[${value}] unknown RoadClass Number value`);
}
}
/**
* Get RoadClass from a String to a Number
*
* @param {number} value String value ["Motorway", "Trunk", "Primary", etc...]
* @returns {string} Road Class
* @example
* sharedstreets.getRoadClassNumber("Motorway"); // => 0
* sharedstreets.getRoadClassNumber("Residential"); // => 5
*/
export function getRoadClassNumber(value: string) {
switch (value) {
case "Motorway": return 0;
case "Trunk": return 1;
case "Primary": return 2;
case "Secondary": return 3;
case "Tertiary": return 4;
case "Residential": return 5;
case "Unclassified": return 6;
case "Service": return 7;
case "Other": return 8;
default: throw new Error(`[${value}] unknown RoadClass String value`);
}
}
/**
* Get FormOfWay from a GeoJSON LineString and/or Optional parameters
*
* @param {number} value Number value [between 0-7]
* @returns {string} Form of Way
* @example
* sharedstreets.getFormOfWayString(0); // => "Undefined"
* sharedstreets.getFormOfWayString(5); // => "TrafficSquare"
*/
export function getFormOfWayString(value: number): string {
switch (value) {
case undefined:
case 0: return "Undefined";
case 1: return "Motorway";
case 2: return "MultipleCarriageway";
case 3: return "SingleCarriageway";
case 4: return "Roundabout";
case 5: return "TrafficSquare";
case 6: return "SlipRoad";
case 7: return "Other";
default: throw new Error(`[${value}] unknown FormOfWay Number value`);
}
}
/**
* Get FormOfWay from a GeoJSON LineString
*
* @param {Feature<LineString>|Array<Array<number>>} line GeoJSON LineString Feature or an Array of Positions
* @param {Object} [options={}] Optional parameters
* @param {number} [options.formOfWay=0] Form of Way
* @example
* const lineA = turf.lineString([[110, 45], [115, 50], [120, 55]], {formOfWay: 3});
* const lineB = turf.lineString([[110, 45], [115, 50], [120, 55]]);
* const lineC = turf.lineString([[110, 45], [115, 50], [120, 55]], {formOfWay: "Motorway"});
*
* sharedstreets.getFormOfWay(lineA); // => 3
* sharedstreets.getFormOfWay(lineB); // => 0
* sharedstreets.getFormOfWay(lineC); // => 1
*/
export function getFormOfWay(
line: Feature<LineString> | LineString | Position[],
options: {
formOfWay?: number | string,
} = {},
): number {
// Set default to Other (0)
let formOfWay: number | string = FormOfWay.Undefined;
// Retrieve formOfWay from Optional Parameters (priority order since it is user defined)
if (options.formOfWay !== undefined) {
formOfWay = options.formOfWay;
// Retrieve formOfWay via GeoJSON LineString properties
} else if (!Array.isArray(line) && line.type === "Feature" && line.properties && line.properties.formOfWay) {
formOfWay = line.properties.formOfWay;
}
// Assert value to Number
if (typeof formOfWay === "string") { formOfWay = getFormOfWayNumber(formOfWay); }
return formOfWay;
}
/**
* Get Start Coordinate from a GeoJSON LineString
*
* @param {Feature<LineString>|Array<Position>} line GeoJSON LineString or an Array of Positiosn
* @returns {Position} Start Coordinate
* @example
* const line = turf.lineString([[110, 45], [115, 50], [120, 55]]);
* const start = sharedstreets.getStartCoord(line);
* start // => [110, 45]
*/
export function getStartCoord(line: Feature<LineString> | LineString | Position[]): Position {
// Array of Positions
if (Array.isArray(line)) {
return line[0];
// GeoJSON Feature
} else if (line.type === "Feature" && line.geometry) {
return line.geometry.coordinates[0];
// GeoJSON Geometry
} else if (line.type === "LineString") {
return line.coordinates[0];
} else {
throw new Error("invalid line");
}
}
/**
* Get Start Coordinate from a GeoJSON LineString
*
* @param {Feature<LineString>|Array<Position>} line GeoJSON LineString or an Array of Positiosn
* @returns {Position} Start Coordinate
* @example
* const line = turf.lineString([[110, 45], [115, 50], [120, 55]]);
* const end = sharedstreets.getEndCoord(line);
* end // => [120, 55]
*/
export function getEndCoord(line: Feature<LineString> | LineString | Position[]): Position {
// Array of Positions
if (Array.isArray(line)) {
return line[line.length - 1];
// GeoJSON Feature
} else if (line.type === "Feature" && line.geometry) {
return line.geometry.coordinates[line.geometry.coordinates.length - 1];
// GeoJSON Geometry
} else if (line.type === "LineString") {
return line.coordinates[line.coordinates.length - 1];
} else {
throw new Error("invalid line");
}
}
/**
* Get FormOfWay from a String to a Number
*
* @param {number} value String value [ex: "Undefined", "Motorway", etc...]
* @returns {number} Form of Way
* @example
* sharedstreets.getFormOfWayNumber("Undefined"); // => 0
* sharedstreets.getFormOfWayNumber("TrafficSquare"); // => 5
*/
export function getFormOfWayNumber(value: string) {
switch (value) {
case undefined:
case "Undefined": return 0;
case "Motorway": return 1;
case "MultipleCarriageway": return 2;
case "SingleCarriageway": return 3;
case "Roundabout": return 4;
case "TrafficSquare": return 5;
case "SlipRoad": return 6;
case "Other": return 7;
default: throw new Error(`[${value}] unknown FormOfWay String value`);
}
}
/**
* getCoords
*
* @param {Feature<LineString>|Array<Array<number>>} line GeoJSON LineString or an Array of positions
* @returns {Array<Array<number>>} Array of positions
* @example
* const line = turf.lineString([[110, 45], [115, 50], [120, 55]]);
* const coords = sharedstreets.getCoords(line);
* coords; // => [[110, 45], [115, 50], [120, 55]]
*/
export function getCoords(line: Feature<LineString> | LineString | number[][]): number[][] {
// Deconstruct GeoJSON LineString
let coords: number[][];
if (isArray(line)) {
coords = line;
} else if (line.type === "Feature") {
if (line.geometry === null) { throw new Error("line geometry cannot be null"); }
coords = line.geometry.coordinates;
} else {
coords = line.coordinates;
}
return coords;
}
/**
* Round Number to 6 decimals
*
* @param {number} num Number to round
* @param {number} [decimalPlaces=6] Decimal Places
* @returns {string} Big Number fixed string
* @example
* sharedstreets.round(10.123456789) // => 10.123457
*/
export function round(num: number, decimalPlaces = 6): string {
return new BigNumber(String(num)).toFixed(decimalPlaces);
}