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

From: Jon Loehrke <>
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 ( ), 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
# haversine.r
# calculates the distance traveled or the angle of displacement with
the Haversine function


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


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

(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

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)

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
T 508-910-6393
F 508-910-6396

        [[alternative HTML version deleted]] mailing list PLEASE do read the posting guide 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 Please read the posting guide before posting to the list.

list of date sections of archive