user13051278
user13051278

Reputation: 23

Unable to calculate the distance using latitude and longitude in R using Haversine formula correctly

geolocation = function(long1, lat1, long2, lat2){
  R = 6371 #Mean radius of the earth in km
  diff.long = (long2-long1)
  diff.lat = (lat2-lat1)
  print(diff.lat)
  a =(sin(diff.lat/2) * sin(diff.lat/2) + cos(lat1) * cos(lat2) * sin(diff.long/2)* sin(diff.long/2))
  c= 2*atan2(sqrt(a),sqrt(1-a))
  d = R*c
  print(d)

  return(d) #Distance in km

}

When I run this with values passed as below it returns as 60.0719 whereas the value is 1.030764

x= geolocation(-73.84431, 40.72132, -73.84161 , 40.71228) print(x)

I am new to R so please excuse me if I have made any silly mistake in the code

Upvotes: 2

Views: 169

Answers (2)

ThomasIsCoding
ThomasIsCoding

Reputation: 101024

Here is a example of using distHaversine from geosphere package, which helps you achieve the same goal:

geolocation = function(long1, lat1, long2, lat2){
  geosphere::distHaversine(c(long1, lat1), c(long2, lat2))/1e3
}

such that

> geolocation(-73.84431, 40.72132, -73.84161 , 40.71228)
[1] 1.031791

Upvotes: 1

Ben
Ben

Reputation: 30474

You need to convert degrees to radians for this formula.

Create an additional function:

deg2rad <- function(deg) return(deg*pi/180)

And use this conversion in your geolocation function:

geolocation = function(long1, lat1, long2, lat2){

  # Convert degrees to radians
  long1 <- deg2rad(long1)
  lat1 <- deg2rad(lat1)
  long2 <- deg2rad(long2)
  lat2 <- deg2rad(lat2)

  R = 6371 #Mean radius of the earth in km

  diff.long = (long2-long1)
  diff.lat = (lat2-lat1)

  a =(sin(diff.lat/2) * sin(diff.lat/2) + cos(lat1) * cos(lat2) * sin(diff.long/2)* sin(diff.long/2))
  c= 2*atan2(sqrt(a),sqrt(1-a))
  d = R*c

  return(d) #Distance in km
}

You should get:

geolocation(-73.84431, 40.72132, -73.84161 , 40.71228)
[1] 1.030637

Alternatively, consider the geosphere package for functions available that will do similar calculations.

Upvotes: 2

Related Questions