Skip to contents

Converts bounding box coordinates to an sfc object with POLYGON geometry.

Usage

bbox_to_poly(bbox = NA, xmin = NA, ymin = NA, xmax = NA, ymax = NA, crs = 4326)

Arguments

bbox

A numeric vector of four bounding box coordinates in the form c(xmin, ymin, xmax, ymax).

xmin, ymin, xmax, ymax

A numeric value specifying an individual bounding box coordinate. Use these arguments as an alternative to bbox.

crs

coordinate reference system, something suitable as input to st_crs

Value

An sfc object with POLYGON geometry and the coordinate reference system specified by crs.

Details

Bounding boxes can be located using online tools such as https://boundingbox.klokantech.com/.

Examples

# Convert the bounding box for Germany.
bbox_GER <- c(5.86631529, 47.27011137, 15.04193189, 55.09916098)

bbox_GER_sf <- bbox_to_poly(bbox_GER)

library(ggplot2)

ggplot(bbox_GER_sf) +
  geom_sf()

# \donttest{
# Extract the bounding box of an `sf` object.
sfobj <- geo_lite_sf("seychelles", points_only = FALSE)

sfobj
#> Simple feature collection with 1 feature and 2 fields
#> Geometry type: MULTIPOLYGON
#> Dimension:     XY
#> Bounding box:  xmin: 45.99888 ymin: -10.46493 xmax: 56.49794 ymax: -3.512
#> Geodetic CRS:  WGS 84
#> # A tibble: 1 × 3
#>   query      address                                                    geometry
#> * <chr>      <chr>                                            <MULTIPOLYGON [°]>
#> 1 seychelles Sesel   (((45.99888 -9.401015, 46.00121 -9.427337, 46.00564 -9.456…

# Require at least one non-empty object.
if (!all(sf::st_is_empty(sfobj))) {
  bbox <- sf::st_bbox(sfobj)

  bbox

  bbox_sfobj <- bbox_to_poly(bbox)

  ggplot(bbox_sfobj) +
    geom_sf(fill = "lightblue", alpha = 0.5) +
    geom_sf(data = sfobj, fill = "wheat")
}

# }