I have a simple polygon and a single point, both having the same crs with lonlat:
library(terra)
pol <- vect("POLYGON ((1 1, 3 1, 3 2, 4 3, 3 4, 2 4, 1 1))",crs="EPSG:4326")
pt <- vect(cbind(3.5,5),crs="EPSG:4326")
I want to calculate the distance between pt
and the nearest point of pol
which is point 5.
I used
terra::distance(pt,pol,unit="km")
but the results are in degrees instead of kilometers:
[1,] 1.118034
Calculating the length of the red line the long way, it turns out to be 123.7 km
perim(as.lines(vect(list(pt,as.points(pol)[5,]))))/1000
Although both x and y are SpatVectors with the same crs, distance
returns degrees. Is this a bug or did I miss something?
I use version 1.7-78 of terra.
According to terra
documentation The distance is always expressed in meter, except when the coordinate reference system is longitude/latitude AND one of the SpatVector(s) consists of lines or polygons. In that case the distance is in degrees, and thus not very useful (this will be fixed soon). Otherwise, results are more precise, sometimes much more precise, when using longitude/latitude rather than a planar coordinate reference system, as these distort distance
Using sf
instead gives the right result
library(terra)
pol <- vect("POLYGON ((1 1, 3 1, 3 2, 4 3, 3 4, 2 4, 1 1))",crs="EPSG:4326")
pt <- vect(cbind(3.5,5),crs="EPSG:4326")
library(sf)
pol <- st_as_sf(pol)
pt <- st_as_sf(pt)
sf::st_distance(pol, pt)
Units: [m]
[,1]
[1,] 124243
The difference with your value 123.7
can be explained by the way sf
computes distance when in degrees (it uses spherical geometry)