Skip to content

Instantly share code, notes, and snippets.

@Robinlovelace
Created February 23, 2017 10:40
Show Gist options
  • Save Robinlovelace/b3970407bf00c4a7b5274ddec0a417db to your computer and use it in GitHub Desktop.
Save Robinlovelace/b3970407bf00c4a7b5274ddec0a417db to your computer and use it in GitHub Desktop.
Find the box edge a point is nearest to
library(stplanr)
d = SpatialPoints(coords = matrix(rnorm(100), ncol = 2))
b = bb2poly(bb = d)
p = raster::geom(b)
for(i in 1:4){
if(i == 1)
l = raster::spLines(rbind(p[i, c("x", "y")], p[i + 1, c("x", "y")])) else
l = raster::bind(
l,
raster::spLines(rbind(p[i, c("x", "y")], p[i + 1, c("x", "y")]))
)
}
l_points = line_midpoint(l)
plot(l)
points(l_points)
l_points$bearing = c("w", "n", "e", "s")
text(x = l_points@coords[,1] + 0.1, y = l_points@coords[,2] + 0.1, l_points$bearing)
p_to_detect = d[5,]
plot(p_to_detect, add = T)
(nearest_one = nabor::knn(data = coordinates(l_points), query = coordinates(p_to_detect), k = 1))
nearest_side = l_points$bearing[nearest_one$nn.idx]
text(x = p_to_detect@coords[,1] + 0.1, y = p_to_detect@coords[,2] + 0.1, nearest_side)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment