Search code examples
rlatitude-longitudegeosphere

Is distm() with distHaversine giving inaccurate results?


I'm confused by this result I'm getting from geosphere::distm(). I compute the distance from a starting point to two points a and b. On Google Maps, I can see that the distance from start to a is greater than the distance from start to b. But the distm() function makes it appear that the reverse is true.

library(geosphere)
start <- c(42.23025, -83.71448)
a <- c(42.30022, -83.71255)
b <- c(42.24302, -83.75135)

# distm() says start is closer to a:

distm(start, a, fun = distHaversine)
#>         [,1]
#> [1,] 879.541
distm(start, b, fun = distHaversine)
#>          [,1]
#> [1,] 4107.282

But NOAA's distance calculator says the distance to a is about 4 miles, compared to about 2 miles for b. And I get a similar ratio of a being nearly twice as a far when I do a simple application of the Pythagorean theorem:

sqrt((start[1] - a[1])^2 + (start[2] - a[2])^2)
#> [1] 0.06999661
sqrt((start[1] - b[1])^2 + (start[2] - b[2])^2)
#> [1] 0.03901884

What explains the result from distm()? My points are close together, less than five miles, could that be contributing?


Solution

  • This looks like a situation of swapping latitude and longitude. (I do this every time.) While the traditional way to communicate a coordinate is Lat,Long, distm is looking for Long,Lat (ie relating to XY). We can swap the order using rev to reverse the order of the coordinate vector.

    distHaversine(rev(start), rev(a))
    [1] 7790.647 # 4.8 miles
    
    distHaversine(rev(start), rev(b))
    [1] 3354.825 # 2 miles