Skip to content

Instantly share code, notes, and snippets.

@obrl-soil
Created February 14, 2019 08:16
Show Gist options
  • Save obrl-soil/5adf8a46325487ea66e99479c1e20730 to your computer and use it in GitHub Desktop.
Save obrl-soil/5adf8a46325487ea66e99479c1e20730 to your computer and use it in GitHub Desktop.
# find the nearest vertex on a polygon to a point
# re: https://twitter.com/EmmaVitz/status/1095574327855001600
library(sf)
nc <- st_read(system.file("shape/nc.shp", package="sf"))
# pick a random state:
nc1 <- nc[sample(seq(nrow(nc)), 1), ]
# always project to a plane before using geos funs!
nc1 <- st_transform(nc1, 32617)
# let's just use the centroid as an arbitrary point from which to measure
nc1c <- st_centroid(nc1)
# break the target polygon down to its component vertices
nc1p <- st_cast(st_geometry(nc1), 'MULTIPOINT')
nc1p <- st_cast(st_geometry(nc1p), 'POINT')
# find the index of the nearest vertex to the centroid
nearest <- st_nearest_feature(nc1c, nc1p)
# plot
plot(nc1[0], col = NA, border = 'grey90', axes = TRUE, reset = FALSE)
plot(nc1p, pch = 19, col = 'grey80', add = TRUE)
plot(nc1c[0], pch = 19, col = 'red', add = TRUE)
plot(nc1p[[nearest]], pch = 19, col = 'blue', add = TRUE)
# \o/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment