SpatialLinesDataFrame:如何计算点和线之间的最小距离

8
我有一份包含街道的SpatialLinesDataFrame,还有一个GPS坐标列表。我需要做的是针对每个GPS坐标获取最近的10条街道名称。
在R中是否有一个函数/包可以计算SpatialLinesDataFrame中的线和点之间的距离?我找不到任何在'sp'中能够帮助我的东西。
有一个相关的问题:Calculating the distance between polygon and point in R,但我想找到线对象和点之间的距离,而不是多边形/点、点/点之间的距离。

搜索:https://dev59.com/ZG_Xa4cB1Zd3GeqP0mQK - IRTFM
这个链接提供了有用的信息,但只展示了如何计算一个点和一个多边形之间的距离。 - Josh O'Brien
1个回答

14

你可以使用 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" 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接