distance-azimuth.pipe.ts 1.49 KB
Newer Older
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
import { Pipe, PipeTransform } from '@angular/core';
import { Place } from './place';
import { getDistanceAzimuth } from './distance-azimuth';

@Pipe({
  name: 'distanceAzimuth'
})
export class DistanceAzimuthPipe implements PipeTransform {
  compassWinds(azimuth: string | number): string {
    const fullwind = 22.5;
    const directions = [
      'N',
      'NNE',
      'NE',
      'ENE',
      'E',
      'ESE',
      'SE',
      'SSE',
      'S',
      'SSW',
      'SW',
      'WSW',
      'W',
      'WNW',
      'NW',
      'NNW',
      'N'
    ];

    // if direction is already in compass points
    if (typeof azimuth === 'string' && directions.indexOf(azimuth) > -1) {
      return azimuth;
    }

    // adjust azimuth if negative
    azimuth = +azimuth;
    while (azimuth < 0) {
      azimuth = azimuth + 360;
    }

    return directions[Math.round((azimuth % 360) / fullwind)];
  }

  kmToMi(km: number): number {
    return km * 0.621371;
  }

  round(raw: number, decimals: number): number {
    const factor = Math.pow(10, decimals);

    return Math.round(raw * factor) / factor;
  }

  transform(place: Place, referencePlace?: Place): any {
    if (!place) {
      return null;
    }

    const distAz = getDistanceAzimuth(place, referencePlace);
    const azimuth = distAz.azimuth;
    const distance = distAz.distance;

    return (
      this.round(distance, 1) +
      ' km ' +
      '(' +
      this.round(this.kmToMi(distance), 1) +
      ' mi) ' +
      this.compassWinds(azimuth)
    );
  }
}