Search code examples
rgispolygonshapefiler-sf

Generating point on polygon border with minimum distance constrain in r


I have seen this solution to generate random point on polygon's border. I was wondering how I could add a minimum distance constrain to this solution ?! For example :

len <- st_length(st_cast(nc_p,"MULTILINESTRING"))

will return the polygon perimeter, and maximum number of points ,n, will be :

n = floor(len/min_distance)

But how the minimum distance should be implemented ?!


Solution

  • You can use type = "regular" as an argument to sf::st_sample() like:

    library(sf)
    library(ggplot2)
    
    nc_p <- st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE)[1, 1]
    nc_l <- st_cast(nc_p, "MULTILINESTRING")
    
    # sample points along line
    min_distance <- 7777
    len <- as.numeric(sf::st_length(nc_l))
    nr_of_poinst <- floor(len / min_distance)
    nc_s <- st_sample(nc_l, nr_of_poinst, type = "regular", exact = TRUE)
    
    ggplot() +
      theme_void() +
      geom_sf(data = nc_p, fill = "grey") +
      geom_sf(data = nc_l, color = "red") +
      geom_sf(data = nc_s, color = "blue")
    

    Created on 2023-02-11 with reprex v2.0.2