I'm trying to find the distance between two points using R. Though I've seen other answers (Find nearest cities from the data frame to the specific location), I want to use a specific formula to calculate distance in miles. On another site (https://andrew.hedges.name/experiments/haversine/), I found this code in Java that gives the correct distance in their GUI:
dlon = lon2 - lon1
dlat = lat2 - lat1
a = (sin(dlat/2))^2 + cos(lat1) * cos(lat2) * (sin(dlon/2))^2
c = 2 * atan2( sqrt(a), sqrt(1-a) )
d = 3961 * c
I then converted this to a function in R:
geo_distance <- function(lon2, lon1, lat2, lat1){
dlon <- lon2 - lon1
dlat <- lat2 - lat1
a <- (sin(dlat/2))^2 + cos(lat1) * cos(lat2) * (sin(dlon/2))^2
c <- 2 * atan2(sqrt(a), sqrt(1-a))
d <- 3961 * c
d
}
#The wrong number of miles from Hong Kong to Grand Canyon
geo_distance(114.17, -112.11, 22.31, 36.11)
#The wrong number of miles from Hong Kong to the Bangkok
geo_distance(114.17, 100.50, 22.31, 13.75)
However, it gives the wrong answer for some locations. For instance, the longitude and latitude of Hong Kong, China is 114.17 and 22.31, for the Grand Canyon, USA they're -112.11 and 36.11, and finally for Bangkok, Thailand they're 100.50 and 13.75.
On the website, it correctly says that Hong Kong and Bangkok are 1075 miles away, and Hong Kong and the Grand Canyon are 7399 miles away. In contrast, my code says that Hong Kong is 8078 miles away from Bangkok and only 4886 miles away from the Grand Canyon!
What is wrong with my code?