Last active
March 23, 2023 19:42
-
-
Save brownag/1b97f2e3af2c1ea63d4a0ef360fd8c5f to your computer and use it in GitHub Desktop.
Convert hydrologic unit IDs to boundaries at the specified level.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#' Convert hydrologic unit IDs to boundaries at the specified level. | |
#' | |
#' Hydrologic unit boundaries are retrieved from the USGS NationalMap ArcGIS MapServer web services: `"https://hydro.nationalmap.gov/arcgis/rest/services/wbd/MapServer/"`. | |
#' | |
#' @param x character. Hydrologic Unit IDs | |
#' @param layerid numeric. `1:8` where `2*layerid` is equal to the number of digits in the Hydrologic Unit Code (HUC). Default: `5` for "HUC-10" watershed. See details. | |
#' @param base_url Default: `"https://hydro.nationalmap.gov/arcgis/rest/services/wbd/MapServer/"` | |
#' @details | |
#' The levels of `layerid` correspond to the numeric codes for the following hydrologic units (HU): | |
#' - WBDLine (0) | |
#' - 2-digit HU (Region) (1) | |
#' - 4-digit HU (Subregion) (2) | |
#' - 6-digit HU (Basin) (3) | |
#' - 8-digit HU (Subbasin) (4) | |
#' - 10-digit HU (Watershed) (5) | |
#' - 12-digit HU (Subwatershed) (6) | |
#' - 14-digit HU (7) | |
#' - 16-digit HU (8) | |
#' @return A `SpatVector` object derived from GeoJSON. | |
#' @export | |
#' @examplesIf !inherits(requireNamespace("terra", quietly = TRUE), 'try-error') | |
#' @examples | |
#' \dontrun{ | |
#' x <- id_to_huc(c("071000050101", "071000050102", "071000050103", "071000050104"), layerid = 6) | |
#' terra::plot(x) | |
#' } | |
id_to_huc <- function(x, | |
layerid = 5, | |
base_url = "https://hydro.nationalmap.gov/arcgis/rest/services/wbd/MapServer/") { | |
stopifnot(requireNamespace("terra")) | |
stopifnot(all(layerid %in% 0:8)) | |
if (length(layerid) < length(x)) { | |
layerid <- rep(layerid, length(x)) | |
} | |
if (length(layerid) != length(x)) { | |
stop("`layerid` should have length 1 or length equal to `x`", call. = FALSE) | |
} | |
res <- lapply(seq_along(x), function(i) { | |
in_id <- utils::URLencode(paste0("huc", layerid[i]*2, "=", shQuote(x[i], type = 'sh'))) | |
queryurl <- paste0(base_url, layerid[i], "/query") | |
urx <- paste0(queryurl, "?WHERE=", in_id, "&f=geojson") | |
terra::vect(urx) | |
}) | |
do.call('rbind', res) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment