Skip to content
Prev 12909 / 29559 Next

Distance from coast

Here's a really simple example using the default low res longlat
coastline in the maps package. It should work for any coastal dataset
that can extract the raw coordinates from, though there's no attempts
at efficiency. spDistsN1 is really fast and works well for this
though, be careful to use longlat argument correctly.

library(sp)

library(maps)

## single point for a simple test
pts <- matrix(c(-88, 36), ncol = 2)

## simple map data
mp <- map("usa", plot = FALSE)

## convert coords to matrix and dump NA
xy.coast <- cbind(mp$x, mp$y)[!is.na(mp$x), ]


## container for all the nearest points matching the input
closest.points <- matrix(0, ncol = 2, nrow = nrow(pts))

for (i in 1:nrow(pts)) {
   closest.points[i, 1:2] <- xy.coast[which.min(spDistsN1(xy.coast,
pts, longlat = TRUE)), ]
}

map(mp)
points(pts)
points(closest.points)

Cheers, Mike.
On Fri, Sep 23, 2011 at 1:11 PM, Sandeep Patil
<sandeep.coepcivil at gmail.com> wrote: