Skip to content

Instantly share code, notes, and snippets.

@ksonda
Created September 20, 2024 04:43
Show Gist options
  • Save ksonda/5ae70a069a35ebe8ef4bd622df73530d to your computer and use it in GitHub Desktop.
Save ksonda/5ae70a069a35ebe8ef4bd622df73530d to your computer and use it in GitHub Desktop.
R-geoconnex
---
title: "Using the geoconnex Reference Feature Server with R"
format:
html:
page-layout: full
---
Below we demonstrates how to use the geoconnex reference feature server API with R's spatial packages, particularly `sf`. We'll explore various use cases for working with hydrological and related spatial data.
## Setup
First, let's load the necessary libraries and set up our API base URL.
```{r setup, message=FALSE}
library(sf)
library(dplyr)
library(mapview)
library(jsonlite)
library(knitr)
library(DT)
base_url <- "https://reference.geoconnex.us"
```
## Use Case 1: Identifying features and their spatial geometry
The Geoconnex Reference Feature server is a source for identifiers and geometries for real-world features that many organizations may collect and publish data about. The attributes of these features vary, but all include a "uri" which serves as a [persistent identifer](https://docs.geoconnex.us/contributing/minting). First, let's discover what kinds of features are available:
```{r collections}
url <- paste0(base_url, "/collections?f=json")
collections <- jsonlite::fromJSON(url)
datatable(collections$collections)
```
We see a number of options available, including watershed boundaries like the Hydrologic Unit Codes, administrative boundaries like counties, states, and public water systems, and hydrologic features like mainstems (rivers) and aquifers, and hydrometric features such as dams and gages. Let's see how to use these collections!
The reference feature server lets us find features according to attribute and spatial filters. Let's say we're interested in a specific river, one we think is called the "Animas river". We can pass an attribute filter query to the "mainstems" collection", and then use the R `sf` package to read into a dataframe, and the `mapview` package to visualize.
```{r mainstem}
# construct a query for a river name that includes the string "Animas"
query <- URLencode("name_at_outlet LIKE '%Animas%'")
url <- paste0(base_url, "/collections/mainstems/items?f=json&filter=", query)
animas_rivers <- st_read(url, quiet = TRUE) %>% select(uri, name_at_outlet)
# Display the results
animas_rivers %>%
select(uri, name_at_outlet) %>%
knitr::kable()
# Map the results
mapview(animas_rivers, zcol = "name_at_outlet")
```
There are evidently 3 rivers that include the word "Animas". Let's say we were interested in the "Animas River", shown on the map in Green. We find that it's Geoconenx URI is `https://geoconnex.us/ref/mainstems/35394`.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment