Class: Quadtree::Point

Inherits:
Object
  • Object
show all
Defined in:
lib/quadtree/point.rb

Overview

Simple coordinate object to represent points in some space.

Since:

  • 1.0.0

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(x, y, data = nil) ⇒ Point

Create a new Quadtree::Point.

Parameters:

  • x (Float)

    X coordinate

  • y (Float)

    Y coordinate

Since:

  • 1.0.0



18
19
20
21
22
# File 'lib/quadtree/point.rb', line 18

def initialize(x, y, data=nil)
  @x = x
  @y = y
  @data = data unless data.nil?
end

Instance Attribute Details

#dataObject

Payload attached to this Quadtree::Point.

Since:

  • 1.0.0



12
13
14
# File 'lib/quadtree/point.rb', line 12

def data
  @data
end

#xFloat

Returns X coordinate.

Returns:

  • (Float)

    X coordinate

Since:

  • 1.0.0



6
7
8
# File 'lib/quadtree/point.rb', line 6

def x
  @x
end

#yFloat

Returns Y coordinate.

Returns:

  • (Float)

    Y coordinate

Since:

  • 1.0.0



9
10
11
# File 'lib/quadtree/point.rb', line 9

def y
  @y
end

Instance Method Details

#distance_to(other) ⇒ Float

This will calculate distance to another, given that they are both on the same flat two dimensional plane.

Parameters:

Returns:

Since:

  • 1.0.0



29
30
31
# File 'lib/quadtree/point.rb', line 29

def distance_to(other)
  Math.sqrt((other.x - self.x) ** 2 + (other.y - self.y) ** 2)
end

#haversine_distance_to(other) ⇒ Float

This will calculate distance to another point using the Haversine formula. This means that it will treat #x as longitude and #y as latitude!

a = sin²(Δφ/2) + cos φ_1 ⋅ cos φ_2 ⋅ sin²(Δλ/2) c = 2 ⋅ atan2( √a, √(1−a) ) d = R ⋅ c

where φ is latitude, λ is longitude, R is earth’s radius (mean radius = 6 371 km); note that angles need to be in radians to pass to trig functions!

Parameters:

Returns:

Since:

  • 1.0.0



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/quadtree/point.rb', line 47

def haversine_distance_to(other)
  # earth's radius
  r = 6371 * 1000.0
  # coverting degrees to radians
  lat1 = self.y * (Math::PI / 180)
  lat2 = other.y * (Math::PI / 180)
  dlat = (other.y - self.y) * (Math::PI / 180)
  dlon = (other.x - self.x) * (Math::PI / 180)

  # a = sin²(Δφ/2) + cos φ_1 ⋅ cos φ_2 ⋅ sin²(Δλ/2)
  a = Math.sin(dlat / 2) * Math.sin(dlat / 2) +
      Math.cos(lat1) * Math.cos(lat2) *
      Math.sin(dlon / 2) * Math.sin(dlon / 2)
  # c = 2 ⋅ atan2( √a, √(1−a) )
  c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a))
  # d = R ⋅ c
  return r * c
end