Skip to content

Instantly share code, notes, and snippets.

@h-a-graham
Created July 3, 2023 10:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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,
#' download the geojson outline of a country
#' @param country character vector of country names
#' @param admin_level character vector of admin levels to download
#' @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")) {
country <- countrycode::countrycode(country,
origin = "country.name",
destination = "iso3c"
)
url <- paste(
"https://www.geoboundaries.org/api/current/gbOpen/",
country, admin_level[1],
sep = "/"
)
get <- httr::GET(url)
cont <- httr::content(get, as = "parsed")
area <- sf::read_sf(cont$gjDownloadURL)
return(area)
}
@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