Class: Drifter::Distance::Haversine

Inherits:
Object
  • Object
show all
Defined in:
lib/drifter/distance/haversine.rb

Constant Summary collapse

EarthRadiusInMiles =
3956
EarthRadiusInKms =
6371
RAD_PER_DEG =

PI/180

0.017453293

Class Method Summary collapse

Class Method Details

.between(point1, point2, options = {}) ⇒ Object

this method is from Landon Cox’s haversine.rb (GNU Affero GPL v3): www.esawdust.com/blog/gps/files/HaversineFormulaInRuby.html: www.esawdust.com (Landon Cox) www.esawdust.com/blog/businesscard/businesscard.html



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/drifter/distance/haversine.rb', line 14

def self.between(point1, point2, options={})
  lat1, lon1 = Drifter.extract_latlng!(point1)
  lat2, lon2 = Drifter.extract_latlng!(point2)

  dlon = lon2 - lon1
  dlat = lat2 - lat1

  dlon_rad = dlon * RAD_PER_DEG 
  dlat_rad = dlat * RAD_PER_DEG

  lat1_rad = lat1 * RAD_PER_DEG
  lon1_rad = lon1 * RAD_PER_DEG

  lat2_rad = lat2 * RAD_PER_DEG
  lon2_rad = lon2 * RAD_PER_DEG

  a = (Math.sin(dlat_rad/2))**2 + Math.cos(lat1_rad) * Math.cos(lat2_rad) * (Math.sin(dlon_rad/2))**2
  c = 2 * Math.atan2( Math.sqrt(a), Math.sqrt(1-a))

  units = options.delete(:units) || Drifter.default_units
  return EarthRadiusInKms * c if units == :km
  return EarthRadiusInMiles * c
end

.to_mysql(options) ⇒ Object

postgresql code seems to work fine fo sql



63
64
65
# File 'lib/drifter/distance/haversine.rb', line 63

def self.to_mysql(options)
  to_postgresql(options)
end

.to_postgresql(options) ⇒ Object

haversine sql based on code.google.com/apis/maps/articles/phpsqlsearch.html you will need to add ‘select’ and ‘AS distance’ if required



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/drifter/distance/haversine.rb', line 41

def self.to_postgresql(options)
  origin = options[:origin]
  lat, lng = Drifter.extract_latlng!(origin)
  lat_column = options[:lat_column] || :lat
  lng_column = options[:lng_column] || :lng
  units = options[:units] || Drifter.default_units
  multiplier = EarthRadiusInMiles
  multiplier = EarthRadiusInKms if units == :km

  postgres = "    \#{multiplier} * ACOS(\n      COS( RADIANS(\#{lat}) ) *\n      COS( RADIANS( \#{lat_column} ) ) *\n      COS( RADIANS( \#{lng_column} ) -\n      RADIANS(\#{lng}) ) +\n      SIN( RADIANS(\#{lat}) ) *\n      SIN( RADIANS( \#{lat_column} ) )\n    )\n  EOS\nend\n"