Skip to content

Instantly share code, notes, and snippets.

@aolinto
Last active November 13, 2015 16:57
Show Gist options
  • Save aolinto/5efff7291791f6f712a0 to your computer and use it in GitHub Desktop.
Save aolinto/5efff7291791f6f712a0 to your computer and use it in GitHub Desktop.
Function to calculate the distance between two points in R
# Calculate distance in kilometers between two points
# https://conservationecology.wordpress.com/2013/06/30/distance-between-two-points-in-r/
# PointDistance tool in the raster
earth.dist <- function (long1, lat1, long2, lat2)
{
rad <- pi/180
a1 <- lat1 * rad
a2 <- long1 * rad
b1 <- lat2 * rad
b2 <- long2 * rad
dlon <- b2 - a2
dlat <- b1 - a1
a <- (sin(dlat/2))^2 + cos(a1) * cos(b1) * (sin(dlon/2))^2
c <- 2 * atan2(sqrt(a), sqrt(1 - a))
R <- 6378.145
d <- R * c
return(d)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment