SpatialLinesDataFrame:如何计算min。点与线之间的距离

时间:2013-10-01 22:21:49

标签: r gis spatial

我有一个带有街道的SpatialLinesDataFrame,我有一个GPS坐标列表。我需要做的是为每个GPS坐标输出最近的10个街道名称。

R中是否有函数/包计算SpatialLinesDataFrame的直线与点之间的距离?我看不到任何对'sp'有帮助的东西。

有一个相关的问题:Calculating the distance between polygon and point in R,但我想找到一个线对象和一个点之间的距离,而不是多边形/点,点/点。

1 个答案:

答案 0 :(得分:13)

您可以使用rgeos::gDistance()byid=TRUE来获取从每个点到每一行的距离矩阵。从那里,提取最接近每个点的10条线的ID相对容易:

library(sp)
library(rgeos)

## Create a SpatialPoints and a SpatialLines object
example("SpatialPoints-class", ask=FALSE, echo=FALSE)
example("SpatialLines-class", ask=FALSE, echo=FALSE)

## Compute the matrix of distances between them.
(m <- gDistance(S, Sl, byid=TRUE))
#          1   2        3        4        5
# a 0.000000 0.0 2.757716 1.414214 2.757716
# b 1.788854 0.5 3.640055 1.000000 3.605551

## And then use it to extract the ids of the 10 (or in this case 1) lines
## closest to each point.
## apply(m, 2, function(X) rownames(m)[order(X)][1:10]) ## Finds 10 closest
apply(m, 2, function(X) rownames(m)[order(X)][1])       ## Finds single closest
#   1   2   3   4   5 
# "a" "a" "a" "b" "a"