get_haversine_distance {eddington} | R Documentation |
Compute the distance between two points using the Haversine formula
Description
Uses the Haversine great-circle distance formula to compute the distance between two latitude/longitude points.
Usage
get_haversine_distance(
lat_1,
lon_1,
lat_2,
lon_2,
units = c("miles", "kilometers")
)
Arguments
lat_1 , lon_1 , lat_2 , lon_2 |
The coordinates used to compute the distance. |
units |
The units of the output distance. |
Value
The distance between two points in the requested units.
References
https://en.wikipedia.org/wiki/Haversine_formula
Examples
# In NYC, 20 blocks == 1 mile. Thus, computing the distance between two
# points along 7th Ave from W 39 St to W 59 St should return ~1 mile.
w39_coords <- list(lat=40.75406905512651, lon=-73.98830604245481)
w59_coords <- list(lat=40.76684156255418, lon=-73.97908243833855)
get_haversine_distance(
w39_coords$lat,
w39_coords$lon,
w59_coords$lat,
w59_coords$lon,
"miles"
)
# The total distance along a sequence of points can be computed. Consider the
# following sequence of points along Park Ave in the form of a list of points
# where each point is a list containing a `lat` and `lon` tag.
park_ave_coords <- list(
list(lat=40.735337983655434, lon=-73.98973648773142), # E 15 St
list(lat=40.74772623378332, lon=-73.98066078090876), # E 35 St
list(lat=40.76026319186414, lon=-73.97149360922498), # E 55 St
list(lat=40.77301604875587, lon=-73.96217737679450) # E 75 St
)
# We can create a function to compute the total distance as follows:
compute_total_distance <- function(coords) {
sum(
sapply(
seq_along(coords)[-1],
\(i) get_haversine_distance(
coords[[i]]$lat,
coords[[i]]$lon,
coords[[i - 1]]$lat,
coords[[i - 1]]$lon,
"miles"
)
)
)
}
# Then applying the function to our sequence results in a total distance.
compute_total_distance(park_ave_coords)
[Package eddington version 4.1.3 Index]