Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SpatialLinesDataFrame: how to calculate the min. distance between a point and a line

Tags:

r

gis

spatial

I have a SpatialLinesDataFrame with streets and I have a list of GPS coordinates. What I need to do is to get out the 10 closest street names for each individual GPS coordinate.

Is there a function/package in R that would calculate the distance between a line and a point for a SpatialLinesDataFrame? I can't see anything that would help in 'sp'.

There is a related question: Calculating the distance between polygon and point in R, but I want to find the distance between a line object and a point, not polygon/point, point/point.

like image 343
Geza Avatar asked Oct 01 '13 22:10

Geza


People also ask

How do you find the shortest distance between a point and a line vector?

The perpendicular distance between a point and a line is the shortest distance between these two objects. In three dimensions, the perpendicular distance, 𝐷 , between a point 𝑃 ( 𝑥 , 𝑦 , 𝑧 )    and a line with direction vector ⃑ 𝑑 is given by 𝐷 = ‖ ‖  𝐴 𝑃 × ⃑ 𝑑 ‖ ‖ ‖ ‖ ⃑ 𝑑 ‖ ‖ , where 𝐴 is any point on the line.


1 Answers

You could use rgeos::gDistance() with byid=TRUE to get a matrix of distances from each point to each line. From there, it's relatively easy to extract the ids of the 10 lines nearest to each point:

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" 
like image 171
Josh O'Brien Avatar answered Oct 19 '22 10:10

Josh O'Brien