I am trying to caculate the distance between two WGS84 points in R. but the results are too high than the real distance.
point1 <- c(34.94821,29.55805)
point2 <- c(34.79130,31.25181)
point_mat <- matrix(c(point1, point2), ncol =2 )
distHaversine(point_mat, r=6378137)
the result is 638845.2, but the real distance between the cities is 188,94 km
Try to understand the formatting of the input to
geosphere::distHaversine()function.In principle, you can define the points "directly" and there is no need to convert them into a matrix form, i.e.
distHaversine(point1, point2). The function defaults to an earth radius in metres. Thus, you could avoid specifying the earth radius (or inject a km-related or other distance unit equivalent).E.g.
Both call yield:
in metres. Thus, ~ 189,15km which is close to your expected result.
If you use the matrix form, make sure the matrix is properly constructed.
You see that the order of longitude/latitude for the points is corrupted (for you), and the value you obtained is for "other" points (than you expect).
In this case, you would have to "load" the matrix with
byrow=TRUEto keep the longitude/latitude in sync:In many use-cases, we operate on data structures that list the "start" and "end" longitudes/latitudes. You can use
cbind()to define the required input todistHaversine()as follows: