Skip to content

Retrieve (get_layer.R) #7

@rellimylime

Description

@rellimylime

get_layer.R is the retrieval layer for the package. It fetches data via the STAC given user specifications.

get_layer() validates inputs, checks the layer exists in the catalog, confirms it is hosted, then reads it through GDAL /vsicurl/ for COG streaming. If a bounding box is supplied, it transforms the bbox to the COG's native raster CRS (EPSG 5070) and crops before returning a SpatRaster.

The function also wraps retrieval in tryCatch so errors are returned with the layer id and URL for easier debugging.

  • get_layer()

    fedex/R/get_layer.R

    Lines 1 to 47 in f191448

    #' Retrieve a WRI layer as raster
    #'
    #' Download and optionally crop a WRI layer to a bounding box. For hosted layers,
    #' this uses COG streaming to fetch only the requested spatial subset.
    #'
    #' @param id Character. Layer name (without .tif extension). Use `list_layers()`
    #' to see available layers.
    #' @param bbox Numeric vector of length 4, optional. Bounding box as c(xmin, ymin, xmax, ymax)
    #' in EPSG:4326 (longitude/latitude). If NULL, returns the full raster.
    #'
    #' @returns A terra SpatRaster object, optionally cropped to the bounding box
    #' @export
    #'
    #' @examples
    #' # Get the full WRI score layer
    #' wri_full <- get_layer("WRI_score")
    #' terra::plot(wri_full)
    #'
    #' # Get WRI score for northern California
    #' bbox_norcal <- c(-122, 37, -121, 38)
    #' wri_norcal <- get_layer("WRI_score", bbox = bbox_norcal)
    #' terra::plot(wri_norcal)
    #'
    #' # Get an air quality resistance indicator
    #' asthma <- get_layer("air_quality_resistance_asthma", bbox = bbox_norcal)
    #' terra::plot(asthma)
    get_layer <- function(id, bbox = NULL) {
    # Validate inputs
    if (missing(id) || is.null(id) || id == "") {
    stop("Layer 'id' is required. Use list_layers() to see available layers.")
    }
    if (!is.null(bbox) && length(bbox) != 4) {
    stop("'bbox' must be a numeric vector of length 4: c(xmin, ymin, xmax, ymax)")
    }
    # Get all layers and find the matching one
    all_layers <- list_layers()
    if (!id %in% all_layers$id) {
    stop(
    "Layer '", id, "' not found in STAC catalog.\n",
    "Available layers: ", paste(head(all_layers$id, 10), collapse = ", "),
    if (nrow(all_layers) > 10) "..." else ""
    )
    }

@FlukeAndFeather

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions