Re: [R] How to calculate the linear distance between 2 points

From: Jon Loehrke <jloehrke_at_umassd.edu>
Date: Mon, 17 Nov 2008 08:18:13 -0500


I have used both the trigonometric identity (a^2 + b^2) = c^2, the haversine and the vincenty equations (http://www.movable-type.co.uk/scripts/latlong.html ), it really depends on how many calculations you need to make, how big of an error you can tolerate, and how far apart your measurements are.

Here is the haversine implementation, let me know if you would like the vincenty version.

haversine<-function(lat1, long1, lat2, long2){

# adapted from Chris Veness JavaScript (c) 2002-2007
# http://www.movable-type.co.uk/
# haversine.r
# calculates the distance traveled or the angle of displacement with
the Haversine function

#coefficients

a<-6378 #Equatorial radius km
b<-6357 #Polar radius km
e<-sqrt(1-b^2/a^2) #eccentricity of the ellipsoid that is Earth

# conversion

TAG_LAT_RAD<-lat1*pi/180
TAG_LONG_RAD<-long1*pi/180
RECAP_LAT_RAD<-lat2*pi/180
RECAP_LONG_RAD<-long2*pi/180
dLat<-RECAP_LAT_RAD-TAG_LAT_RAD
dLong<-RECAP_LONG_RAD-TAG_LONG_RAD

#calculates dist traveled using the Haversine function from release
and recapture positions in radians         

hav<-(sin((dLat)/2))^2+
(cos(TAG_LAT_RAD)*cos(RECAP_LAT_RAD)*(sin((dLong)/2))^2) dist_travel_rad<-2*atan2(sqrt(hav),sqrt(1-hav)) #ie half the versed sine...the haversine formula
#distance traveled conversion, ie multplying by R with autocorrelating
R by latitude
DIST_TRAVEL_KM<-dist_travel_rad*(a*(1-e^2))/(1- e^2*(sin(mean(c(TAG_LAT_RAD, RECAP_LAT_RAD)))^2)^(3/2))# define new vector

# calculation of angular displacement

y<-sin(dLong)*cos(RECAP_LAT_RAD)
x<-cos(TAG_LAT_RAD)*sin(RECAP_LAT_RAD)- sin(TAG_LAT_RAD)*cos(RECAP_LAT_RAD)*cos(dLong) PHI_RAD<-2*pi-atan2(y,x)
PHI_DEG<-((PHI_RAD*180.0/pi)+360.0)%%360.0
#output

S<-list()
S$Dist_km<-DIST_TRAVEL_KM # distance traveled in Km S$PHI_DEG<-PHI_DEG # Angular displacement from North in deg. S
}

Jon Loehrke
Graduate Research Assistant
Department of Fisheries Oceanography
School for Marine Science and Technology University of Massachusetts
200 Mill Road, Suite 325
Fairhaven, MA 02719
jloehrke_at_umassd.edu
T 508-910-6393
F 508-910-6396

        [[alternative HTML version deleted]]



R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Mon 17 Nov 2008 - 13:23:11 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Mon 17 Nov 2008 - 14:30:25 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive