-
-
Save wallace/6127633 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class StationLog < ActiveRecord::Base | |
belongs_to :boat_log | |
has_many :rep_logs, :dependent => :destroy | |
accepts_nested_attributes_for :rep_logs, :reject_if => lambda { |a| a[:replicate].blank? }, :allow_destroy => true | |
EARTH_RADIUS = 6371000 # Earth's radius in meters | |
# convert degrees to radians | |
def self.convDegRad(value) | |
unless value.nil? or value == 0 | |
value = (value/180) * Math::PI | |
end | |
return value | |
end | |
def self.coorDist | |
stn1 = Station.station_one # Station.station_one == Station.find(1) | |
stn2 = Station.station_two # Station.station_two == Station.find(2) | |
deltaLat = (stn2.latitude - stn1.latitude) | |
deltaLon = (stn2.longitude - stn1.longitude) | |
deltaLat = convDegRad(deltaLat) | |
deltaLon = convDegRad(deltaLon) | |
# Calculate square of half the chord length between latitude and longitude | |
a = Math.sin(deltaLat/2) * Math.sin(deltaLat/2) + | |
Math.cos((stn1.latitude/180 * Math::PI)) * Math.cos((stn2.latitude/180 * Math::PI)) * | |
Math.sin(deltaLon/2) * Math.sin(deltaLon/2); | |
# Calculate the angular distance in radians | |
c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)) | |
distance = EARTH_RADIUS * c | |
return distance | |
end | |
end | |
from console log... | |
irb(main):032:0> BoatLog.first.station_logs.coorDist | |
BoatLog Load (0.4ms) SELECT "boat_logs".* FROM "boat_logs" LIMIT 1 | |
StationLog Load (0.2ms) SELECT "station_logs".* FROM "station_logs" WHERE "station_logs"."boat_log_id" = 4 AND "station_logs"."stn_number" = 1 LIMIT 1 | |
StationLog Load (0.3ms) SELECT "station_logs".* FROM "station_logs" WHERE "station_logs"."boat_log_id" = 4 AND "station_logs"."stn_number" = 1 LIMIT 1 | |
StationLog Load (0.2ms) SELECT "station_logs".* FROM "station_logs" WHERE "station_logs"."boat_log_id" = 4 AND "station_logs"."stn_number" = 2 LIMIT 1 | |
StationLog Load (0.2ms) SELECT "station_logs".* FROM "station_logs" WHERE "station_logs"."boat_log_id" = 4 AND "station_logs"."stn_number" = 2 LIMIT 1 | |
=> 3428.1395884519347 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment