I want to calculate the Euclidean distance between (2000) points scattered on an island and the shoreline. I have the points, a polygon of the island and also a polyline file of the coast in separate shapefiles. All files are georeferenced and all points are marked with x and y coordinates.

Is there a way to easily do this, preferably in a for loop so I get all the distances with a single code.

I already read that the package mapstat is useful, but I am somehow not able to install it.

Any tips will be welcome!


You could use gDistance from the rgeos package:

line <- readWKT("LINESTRING(1 0, 0.2 0, 0 0.2, 0 1)")
pt <- readWKT("GEOMETRYCOLLECTION(POINT(1.1 0.1), POINT(0.2 0.2), POINT(0.1 1))")

# [1] "SpatialPoints"
# attr(,"package")
# "sp"
# [1] "SpatialLines"
# attr(,"package")
# [1] "sp"

plot(pt, axes=TRUE, xlim=c(-0.1, 1.2))
plot(line, add=TRUE)


# distances between the two geometries in the units of the current projection;
# use planar coordinates for euclidean distances;
# byid=TRUE calculate distance for every point

gDistance(pt, line, byid=TRUE)
#        1      2   3
# 1 0.1414 0.1414 0.1
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.