# R find length along line from origin to another point

In R, I have a collection of points (~15,000) on the boundary of a polygon. For every point, I want to calculate the distance from the origin vertex (1st plotted vertex of the polygon).

I have a method that works (below) - using the lengthToPoint function defined here (with the print(paste("Found...) line commented out) - but I cannot find a quick function for distance along a line for a Spatialpointsdataframe (or whatever format) or for more than 1 point at a time.

``````require(maptools)
require(sp)
require(rgeos)

# create a dummy polygon: coordinates, promote to Polygons and SpatialPolygons
coordsPol = cbind(c(1,2,3,4,4),c(3,2,2,1,3))
verts <- rbind(coordsPol, coordsPol[1, ])
pol <- SpatialPolygons(list(Polygons(list(Polygon(verts)), ID="a")))

# create spatialpointsdataframe (they all fall inside the polygon)
p = data.frame(x=c(1.5,2.5,2.75,4,3.5),y=c(2.5,2,2,1.3,3),ID=c("a","b","c","d","e"))
coordinates(p) <- ~x+y

# the polygon needs to be a SpatialLines object for the lengthToPoint fucntion
l <- as(pol,"SpatialLines")

# the SPDF needs to be SpatialPoints for the lengthToPoint function
pm <- as(p,"SpatialPoints")

# create a vector of distances from the origin using lengthToPoint as this can
# only take one point at a time
# https://gis.stackexchange.com/questions/209254/calculate-distance-of-points-spatialpoints-object-along-a-path-spatialline
lenvec <- vector()
for(pp in 1:length(pm)){
lenvec[pp] <- lengthToPoint(l,pm[pp])
}

p@data\$dist <- lenvec
``````
• Is there a function that returns the distance along a line from the origin for > 1 point at a time?
• I think if you loop over the polygon segments, find the points that are on the current segment, then you can compute the distance for all those points as the distance along that segment plus the distance to the first vertex of that segment. Proceed to the next segment... Commented Feb 12, 2018 at 17:08

## 1 Answer

Try `rgeos::gProject`:

``````coordinates(l)
# [[1]]
# [[1]][[1]]
#      [,1] [,2]
# [1,]    1    3
# [2,]    4    3
# [3,]    4    1
# [4,]    3    2
# [5,]    2    2
# [6,]    1    3

p
#   coordinates ID
# 1  (1.5, 2.5)  a
# 2    (2.5, 2)  b
# 3   (2.75, 2)  c
# 4    (4, 1.3)  d
# 5    (3.5, 3)  e

rgeos::gProject(l, p, normalized=FALSE)
# [1] 8.121 6.914 6.664 4.700 2.500

plot(l, axes=TRUE, col="grey")
points(p, col="red", pch=19)
text(p)
``````

• I think gProject solves Sam's other problem gis.stackexchange.com/questions/271166/… Commented Feb 12, 2018 at 18:09
• gProject does indeed solve this particular problem of taking multiple points on a line and finding the distance from origin, thanks
– Sam
Commented Feb 14, 2018 at 8:43