Module: Geocoder::Calculations

Extended by:
Calculations
Included in:
Calculations
Defined in:
lib/geocoder/calculations.rb

Constant Summary collapse

COMPASS_POINTS =

Compass point names, listed clockwise starting at North.

If you want bearings named using more, fewer, or different points override Geocoder::Calculations.COMPASS_POINTS with your own array.

%w[N NE E SE S SW W NW]
EARTH_RADIUS =

Radius of the Earth, in kilometers. Value taken from: en.wikipedia.org/wiki/Earth_radius

6371.0
KM_IN_MI =

Conversion factor: multiply by kilometers to get miles.

0.621371192

Instance Method Summary collapse

Instance Method Details

#bearing_between(lat1, lon1, lat2, lon2, options = {}) ⇒ Object

Calculate bearing between two sets of coordinates. Returns a number of degrees from due north (clockwise).

Also accepts an options hash:

  • :method - :linear (default) or :spherical; the spherical method is “correct” in that it returns the shortest path (one along a great circle) but the linear method is the default as it is less confusing (returns due east or west when given two points with the same latitude)

Based on: www.movable-type.co.uk/scripts/latlong.html



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
# File 'lib/geocoder/calculations.rb', line 79

def bearing_between(lat1, lon1, lat2, lon2, options = {})
  options[:method] = :linear unless options[:method] == :spherical

  # convert degrees to radians
  lat1, lon1, lat2, lon2 = to_radians(lat1, lon1, lat2, lon2)

  # compute deltas
  dlat = lat2 - lat1
  dlon = lon2 - lon1

  case options[:method]
  when :linear
    y = dlon
    x = dlat

  when :spherical
    y = Math.sin(dlon) * Math.cos(lat2)
    x = Math.cos(lat1) * Math.sin(lat2) -
        Math.sin(lat1) * Math.cos(lat2) * Math.cos(dlon)
  end

  bearing = Math.atan2(x,y)
  # Answer is in radians counterclockwise from due east.
  # Convert to degrees clockwise from due north:
  (90 - to_degrees(bearing) + 360) % 360
end

#bounding_box(latitude, longitude, radius, options = {}) ⇒ Object

Returns coordinates of the lower-left and upper-right corners of a box with the given point at its center. The radius is the shortest distance from the center point to any side of the box (the length of each side is twice the radius).

This is useful for finding corner points of a map viewport, or for roughly limiting the possible solutions in a geo-spatial search (ActiveRecord queries use it thusly).



160
161
162
163
164
165
166
167
168
169
# File 'lib/geocoder/calculations.rb', line 160

def bounding_box(latitude, longitude, radius, options = {})
  units = options[:units] || :mi
  radius = radius.to_f
  [
    latitude  - (radius / latitude_degree_distance(units)),
    longitude - (radius / longitude_degree_distance(latitude, units)),
    latitude  + (radius / latitude_degree_distance(units)),
    longitude + (radius / longitude_degree_distance(latitude, units))
  ]
end

#compass_point(bearing, points = COMPASS_POINTS) ⇒ Object

Translate a bearing (float) into a compass direction (string, eg “North”).



109
110
111
112
# File 'lib/geocoder/calculations.rb', line 109

def compass_point(bearing, points = COMPASS_POINTS)
  seg_size = 360 / points.size
  points[((bearing + (seg_size / 2)) % 360) / seg_size]
end

#distance_between(lat1, lon1, lat2, lon2, options = {}) ⇒ Object

Calculate the distance between two points on Earth (Haversine formula). Takes two sets of coordinates and an options hash:

  • :units - :mi (default) or :km



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

def distance_between(lat1, lon1, lat2, lon2, options = {})

  # set default options
  options[:units] ||= :mi

  # convert degrees to radians
  lat1, lon1, lat2, lon2 = to_radians(lat1, lon1, lat2, lon2)

  # compute deltas
  dlat = lat2 - lat1
  dlon = lon2 - lon1

  a = (Math.sin(dlat / 2))**2 + Math.cos(lat1) *
      (Math.sin(dlon / 2))**2 * Math.cos(lat2)
  c = 2 * Math.atan2( Math.sqrt(a), Math.sqrt(1-a))
  c * earth_radius(options[:units])
end

#earth_radius(units = :mi) ⇒ Object

Radius of the Earth in the given units (:mi or :km). Default is :mi.



216
217
218
# File 'lib/geocoder/calculations.rb', line 216

def earth_radius(units = :mi)
  units == :km ? EARTH_RADIUS : to_miles(EARTH_RADIUS)
end

#geographic_center(points) ⇒ Object

Compute the geographic center (aka geographic midpoint, center of gravity) for an array of geocoded objects and/or [lat,lon] arrays (can be mixed). Any objects missing coordinates are ignored. Follows the procedure documented at www.geomidpoint.com/calculation.html.



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
# File 'lib/geocoder/calculations.rb', line 120

def geographic_center(points)

  # convert objects to [lat,lon] arrays and remove nils
  points.map!{ |p| p.is_a?(Array) ? p : p.to_coordinates }.compact

  # convert degrees to radians
  points.map!{ |p| to_radians(p) }

  # convert to Cartesian coordinates
  x = []; y = []; z = []
  points.each do |p|
    x << Math.cos(p[0]) * Math.cos(p[1])
    y << Math.cos(p[0]) * Math.sin(p[1])
    z << Math.sin(p[0])
  end

  # compute average coordinate values
  xa, ya, za = [x,y,z].map do |c|
    c.inject(0){ |tot,i| tot += i } / c.size.to_f
  end

  # convert back to latitude/longitude
  lon = Math.atan2(ya, xa)
  hyp = Math.sqrt(xa**2 + ya**2)
  lat = Math.atan2(za, hyp)

  # return answer in degrees
  to_degrees [lat, lon]
end

#km_in_miObject

Conversion factor: km to mi.



223
224
225
# File 'lib/geocoder/calculations.rb', line 223

def km_in_mi
  KM_IN_MI
end

#latitude_degree_distance(units = :mi) ⇒ Object

Calculate the distance spanned by one degree of latitude in the given units.



28
29
30
# File 'lib/geocoder/calculations.rb', line 28

def latitude_degree_distance(units = :mi)
  2 * Math::PI * earth_radius(units) / 360
end

#longitude_degree_distance(latitude, units = :mi) ⇒ Object

Calculate the distance spanned by one degree of longitude at the given latitude. This ranges from around 69 miles at the equator to zero at the poles.



37
38
39
# File 'lib/geocoder/calculations.rb', line 37

def longitude_degree_distance(latitude, units = :mi)
  latitude_degree_distance(units) * Math.cos(to_radians(latitude))
end

#mi_in_kmObject

Conversion factor: mi to km.



230
231
232
# File 'lib/geocoder/calculations.rb', line 230

def mi_in_km
  1.0 / KM_IN_MI
end

#to_degrees(*args) ⇒ Object

Convert radians to degrees. If an array (or multiple arguments) is passed, converts each value and returns array.



190
191
192
193
194
195
196
197
# File 'lib/geocoder/calculations.rb', line 190

def to_degrees(*args)
  args = args.first if args.first.is_a?(Array)
  if args.size == 1
    (args.first * 180.0) / Math::PI
  else
    args.map{ |i| to_degrees(i) }
  end
end

#to_kilometers(mi) ⇒ Object

Convert miles to kilometers.



202
203
204
# File 'lib/geocoder/calculations.rb', line 202

def to_kilometers(mi)
  mi * mi_in_km
end

#to_miles(km) ⇒ Object

Convert kilometers to miles.



209
210
211
# File 'lib/geocoder/calculations.rb', line 209

def to_miles(km)
  km * km_in_mi
end

#to_radians(*args) ⇒ Object

Convert degrees to radians. If an array (or multiple arguments) is passed, converts each value and returns array.



176
177
178
179
180
181
182
183
# File 'lib/geocoder/calculations.rb', line 176

def to_radians(*args)
  args = args.first if args.first.is_a?(Array)
  if args.size == 1
    args.first * (Math::PI / 180)
  else
    args.map{ |i| to_radians(i) }
  end
end