geographicBoundingBox.js 1.93 KB
Newer Older
Athanasios's avatar
Athanasios committed
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
const boxIntersect = require("box-intersect");
const angle = require("./angle");

class GeographicBoundingBox {

  constructor(minLong, minLat, maxLong, maxLat) {
    this.minLong = minLong;
    this.minLat = minLat;
    this.maxLong = maxLong;
    this.maxLat = maxLat;
  }

  extend(percent) {
    percent *= 0.01;
    let diffLon = (this.maxLong - this.minLong) * percent;
    let diffLat = (this.maxLat - this.minLat) * percent;
    this.minLong -= diffLon;
    this.maxLong += diffLon;
    this.minLat -= diffLat;
    this.maxLat += diffLat;
  }

  getCorners() {

    return [
      this.minLong,
      this.minLat,
      this.maxLong,
      this.maxLat
    ];

  }

  intersectWith(gbb) {

    let overlaps = boxIntersect([
      this.getCorners(),
      gbb.getCorners()
    ]);

    if (overlaps.length > 0) {
      return true;
    }
    return false;
  }

  intersectWithGeographic(geographic) {
    if (this.minLong <= geographic.longitude &&
      this.maxLong >= geographic.longitude &&
      this.minLat <= geographic.latitude &&
      this.maxLat >= geographic.latitude) {
      return true;
    }
    return false;
  }

  clone() {
    return new GeographicBoundingBox(...this.getCorners());
  }

}

const fromString = (str) => {
athanasios's avatar
athanasios committed
64
  if(!str) return null;
Athanasios's avatar
Athanasios committed
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
  let tokens = str.split(",");
  return new GeographicBoundingBox(...tokens.map(token => parseFloat(token)));
}

const fromBoundingSphere = (boundingSphere) => {
  let center = boundingSphere.geographicCenter;
  let deltaLat = angle.roughDistanceToLatitude(boundingSphere.radius);
  let deltaLong = angle.roughDistanceToLongitude(center.latitude, boundingSphere.radius);
  return new GeographicBoundingBox(
    center.longitude - deltaLong,
    center.latitude - deltaLat,
    center.longitude + deltaLong,
    center.latitude + deltaLat
  );
}

module.exports = { GeographicBoundingBox, fromString, fromBoundingSphere };