#' Expand bbox
#'
#' A function to take a bounding box (generated using st_bbox) and expand it by x meters in the X direction and y meters in the Y direction.
#'
#' @param bbox a bounding box generated by sf::st_bbox() or named numeric vector with xmin, ymin, xmax, ymax.
#' @param X the distance in metres that we want to expand the bounding box by in the X direction
#' @param Y the distance in metres that we want to expand the bounding box by in the Y direction
#' @param X2 if specified, the meters in the Easterly direction and metresX becomes metres in the Westerly direction.
#' @param Y2 if specified, the metres to the South. metresY becomes metres to the North.
#' @param crs_out what epsg coordinate system to return the bbox in. Defaults to lat/lng (4326).
#'
#' @return a named numeric vector of bbox extents. This can be converted into an sf object using sf::st_as_sfc(). Coordinates are in lat/lng (4326).
#'
#' @examples
#' library(sf)
#' camden <- dplyr::filter(localauth_data, Name == "Camden") %>%
#' st_transform(4326)
#' bbox <- expand_bbox(st_bbox(camden), 5000, 5000)
#'
#' library(ggplot2)
#' ggplot() +
#' base_map(bbox, increase_zoom = 2) +
#' geom_sf(data = camden, fill = NA) +
#' coord_sf(
#' xlim = c(bbox["xmin"], bbox["xmax"]),
#' ylim = c(bbox["ymin"], bbox["ymax"]), crs = 4326
#' )
#' @export
expand_bbox <- function(bbox, X, Y, X2 = X, Y2 = Y,
crs_out = 4326) {
bbox <- bbox %>%
st_as_sfc() %>%
sf::st_transform(crs = 4326) %>%
st_bbox()
bbox["xmin"] <- bbox["xmin"] - (X / 6370000) * (180 / pi) / cos(bbox["xmin"] * pi / 180)
bbox["xmax"] <- bbox["xmax"] + (X2 / 6370000) * (180 / pi) / cos(bbox["xmax"] * pi / 180)
bbox["ymin"] <- bbox["ymin"] - (Y / 6370000) * (180 / pi)
bbox["ymax"] <- bbox["ymax"] + (Y2 / 6370000) * (180 / pi)
bbox %>%
st_as_sfc() %>%
sf::st_transform(crs = crs_out) %>%
st_bbox()
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.