Skip to content

Instantly share code, notes, and snippets.

@h-a-graham
Last active November 28, 2024 19:44
Show Gist options
  • Save h-a-graham/e9bb64cd7e9e2e2d68052009b713f4d1 to your computer and use it in GitHub Desktop.
Save h-a-graham/e9bb64cd7e9e2e2d68052009b713f4d1 to your computer and use it in GitHub Desktop.
Get admin boundaries for any country with R.
#' @title Get administritive outlines for a country
#' @description using the geoBoundaires API, get the administritive polygon(s)
#' for a country
#' @param country character vector: a country name
#' @param admin_level character vector: the admin level to download
#' @param quiet logical, should st_read be quiet?
#' @return sf object of the outlines
#' @details check out the documentation for the geoboundaries API at:
#' geoBoundaries.org
#'
geo_bounds <- function(
country,
admin_level = c("ADM0", "ADM1", "ADM2"),
quiet = TRUE) {
# assertions
country <- rlang::arg_match(
country,
unique(countrycode::countryname_dict$country.name.en)
)
admin_level <- rlang::arg_match(admin_level)
assertthat::assert_that(inherits(quiet, "logical"))
# get the iso3c code for the country
country <- countrycode::countrycode(country,
origin = "country.name",
destination = "iso3c"
)
# get the geojson file
url <- paste(
"https://www.geoboundaries.org/api/current/gbOpen/",
country, admin_level,
sep = "/"
)
get <- httr::GET(url)
cont <- httr::content(get, as = "parsed")
sf::st_read(cont$gjDownloadURL, drivers = "GeoJSON", quiet = quiet)
}
@h-a-graham
Copy link
Author

usage:

x <- geo_bounds("United Kingdom")
plot(x["geometry"])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment