Skip to content

Instantly share code, notes, and snippets.

@ryan-hill
Last active April 10, 2019 20:32
Show Gist options
  • Save ryan-hill/3649cc0cc636a5a333a65cc49c46bdcf to your computer and use it in GitHub Desktop.
Save ryan-hill/3649cc0cc636a5a333a65cc49c46bdcf to your computer and use it in GitHub Desktop.
library(jsonlite);library(sf);library(sp);library(geojsonio)
watershed = function(state, lon, lat, sf=TRUE){
p1 = 'https://streamstats.usgs.gov/streamstatsservices/watershed.geojson?rcode='
p2 = '&xlocation='
p3 = '&ylocation='
p4 = '&crs=4326&includeparameters=false&includeflowtypes=false&includefeatures=true&simplify=true'
query <- paste0(p1, state, p2, toString(lon), p3, toString(lat), p4)
mydata <- fromJSON(query, simplifyVector = FALSE, simplifyDataFrame = FALSE)
poly_geojsonsting <- toJSON(mydata$featurecollection[[2]]$feature, auto_unbox = TRUE)
if(sf){
poly <- st_read(poly_geojsonsting, quiet=T)
}else{
poly <- geojson_sp(poly_geojsonsting)
}
poly
}
#Example: Delineate Calapooia River, OR
lon = -123.1121
lat = 44.6390
state = 'OR'
#Watershed example as sp object
ws = watershed(state, lon, lat, sf=F)
plot(ws, col='red')
#Watershed example as sf object
ws = watershed(state, lon, lat, sf=T)
plot(ws$geometry, col='red')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment