Skip to content

Instantly share code, notes, and snippets.

@mhweber
Forked from ksonda/usgs_sta_mainstem.R
Created December 6, 2022 20:07
Show Gist options
  • Save mhweber/dd33783e1f6ec5c49a240a7bcb88146c to your computer and use it in GitHub Desktop.
Save mhweber/dd33783e1f6ec5c49a240a7bcb88146c to your computer and use it in GitHub Desktop.
library(sf)
library(mapview)
# read identifiers for Colorado River and Colorado River (TX) into simple features
colorado_river <- sf::read_sf("https://geoconnex.us/ref/mainstems/29559")
colorado_river_tx <- sf::read_sf("https://geoconnex.us/ref/mainstems/2639515")
## Function that constructs query to retrive the latest discharge observation from the USGS
## SensorThings API endpoint for a given geoconnex mainstem uri
latest_obs_by_mainstem <- function(mainstem_uri){
url <- paste0(
"https://labs.waterdata.usgs.gov/sta/v1.1/", #USGS SensorThings API Endpoint
"Locations?$filter=properties/mainstemURL%20eq%20%27", # Filter locations by mainstem URI
mainstem_uri, #pipe in desired URI from function parameter
"%27&$expand=Things($select=id)", #Get the gage at the location
"/Datastreams($filter=properties/ParameterCode%20eq%20%2700060%27;$select=description)", #get discharge data
"/Observations($top=1;$select=result,phenomenonTime;$orderBy=phenomenonTime%20desc)", #get the most recent reading
"&$resultFormat=GeoJSON" #return as GeoJSON
)
result <- sf::read_sf(url)
result$discharge_cfs <- as.numeric(result$`Things/0/Datastreams/0/Observations/0/result`)
result <- result[which(!is.na(result$discharge_cfs)),]
return(result)
}
## map the two rivers
m <- mapview(colorado_river,color="purple") + mapview(colorado_river_tx,color="orange")
m
## add Colorado River discharges
CR <- latest_obs_by_mainstem("https://geoconnex.us/ref/mainstems/29559")
m <- m + mapview(CR,zcol='discharge_cfs',layer.name="latest discharge on Colorado River")
m
## add Colorado River (TX) discharges
CR_TX <- latest_obs_by_mainstem("https://geoconnex.us/ref/mainstems/2639515")
m <- m + mapview(CR_TX,zcol='discharge_cfs',layer.name="latest discharge on Colorado River (TX)")
m
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment