简体   繁体   中英

How to get the max distance from a point within a polygon in R

I have a series of polygons and points with each polygon containing a point. I want to determine the maximum distance of each point to the edge of the polygon containing it is contained within in R. 具有内部点的示例多边形

I looked at using the rgeos gDistance function but this returns 0 for points within polygons.

Using an example polygon and a point that falls within the polygon this is what i've coded so far but i'm getting a distance of 0 rather than the distance from a point to polygon edges.

pt1 = readWKT("POINT(0.5 0.25)")
p1 = readWKT("POLYGON((0 0,1 0,1 1,0 1,0 0))")

gDistance(pt1, p1)
# 0

Does a function exist in R or an R package that can determine distances for points within polygons to the polygon edge?

Much appreciated within advance.

Solution using spatstat and the built-in dataset chorley :

library(spatstat)
W <- Window(chorley) # Polygonal window of the choley dataset
p <- list(x = c(350, 355), y = c(415, 425)) # Two points in polygon
plot(W, main = "")
points(p, col = c("red", "blue"), cex = 1.5)

v <- vertices(W) # Polygon vertices
d <- crossdist(v$x, v$y, p$x, p$y) # 2-column matrix of cross distances
i1 <- which.max(d[,1]) # Index of max dist for first (red) point
i2 <- which.max(d[,2]) # Index of max dist for second (blue) point

plot(W, main = "")
points(p, col = c("red", "blue"), cex = 1.5)
points(v$x[c(i1,i2)], v$y[c(i1,i2)], col = c("red", "blue"), cex = 1.5)

d[i1,1] # Max dist for first (red) point
#> [1] 21.35535
d[i2,2] # Max dist for second (blue) point
#> [1] 15.88226

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM