Skip to contents

Find the shortest path between start and end points within a polygon

Usage

cnt_path(skeleton, start_point, end_point)

Arguments

skeleton

an output from cnt_skeleton() function

start_point

one or more starting points. It should be of the same class as the skeleton parameter

end_point

one ending point of the same class as skeleton and start_point parameters.

Value

a list of sf, sfc, SpatVector or geos_geometry class objects of a LINESTRING geometry

Details

The following function uses the sfnetworks::st_network_paths() approach to connect start_point with end_point by using the skeleton of a closed polygon as potential routes.

It is important to note that multiple starting points are permissible, but there can only be one ending point. Should there be two or more ending points, the algorithm will return an error.

Neither starting nor ending points are required to be located on the edges of a polygon (i.e., snapped to the boundary); they can be positioned wherever possible inside the polygon.

The algorithm identifies the closest nodes of the polygon's skeleton to the starting and ending points and then connects them using the shortest path possible along the skeleton. Therefore, if more precise placement of start and end points is necessary, consider executing the cnt_skeleton() function with the keep = 1 option. In doing so, the resulting skeleton may be more detailed, increasing the likelihood that the starting and ending points are already situated on the skeleton paths.

Examples

library(sf)
#> Linking to GEOS 3.10.2, GDAL 3.4.1, PROJ 8.2.1; sf_use_s2() is TRUE
library(geos)
# Load Polygon and points data
polygon <-
  sf::st_read(
    system.file("extdata/example.gpkg", package = "centerline"),
    layer = "polygon",
    quiet = TRUE
  ) |>
  geos::as_geos_geometry()

points <-
  sf::st_read(
    system.file("extdata/example.gpkg", package = "centerline"),
    layer = "polygon_points",
    quiet = TRUE
  ) |>
  geos::as_geos_geometry()

# Find polygon's skeleton
pol_skeleton <- cnt_skeleton(polygon)

# Connect points
pol_path <-
  cnt_path(
    skeleton = pol_skeleton,
    start_point = points[2],
    end_point = points[1]
  )

# Plot
plot(polygon)
plot(pol_skeleton, col = "blue", add = TRUE)
plot(points[1:2], col = "red", add = TRUE)
plot(pol_path, lwd = 3, add = TRUE)