Last active
November 28, 2022 15:44
-
-
Save ksonda/1519a1f1e1e483a860b2107ca201f93d to your computer and use it in GitHub Desktop.
R sparql demo for geoconnex
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
##packages used | |
require(sf) | |
require(SPARQL) | |
# remotes::install_github("cran/SPARQL") this is archived by cran grrrr | |
require(mapview) | |
require(dplyr) | |
library(stringi) | |
# start gage | |
gage_uri <- "https://geoconnex.us/ref/gages/1118104" | |
start_gage <- sf::read_sf(gage_uri) | |
#define function that takes a gage uri and feeds it into a SPARQL query that | |
#identifies all features that have the same linearElement as a referencedPosition | |
#and returns those features and the mainstem as sf objects | |
find_mainstem_from_gage <- function(gage_uri){ | |
endpoint <- "https://graph.geoconnex.us/repositories/iow" | |
query <- paste0("PREFIX hyf: <https://www.opengis.net/def/schema/hy_features/hyf/> | |
PREFIX schema: <https://schema.org/> | |
PREFIX geo: <http://www.opengis.net/ont/geosparql#> | |
select DISTINCT ?mainstem ?gage ?name (str(?gwkt) AS ?gage_geom) (str(?mswkt) AS ?mainstem_geom) | |
where { <", | |
gage_uri, | |
"> hyf:referencedPosition ?rp . | |
?rp hyf:HY_IndirectPosition ?ip . | |
?ip hyf:linearElement ?mainstem . | |
BIND (?mainstem as ?target) | |
?gage hyf:referencedPosition ?rp2 . | |
?rp2 hyf:HY_IndirectPosition ?ip2. | |
?ip2 hyf:linearElement ?target . | |
?mainstem schema:name ?name . | |
?mainstem geo:hasGeometry ?msgeom . | |
?msgeom geo:asWKT ?mswkt . | |
?gage geo:hasGeometry ?ggeom . | |
?ggeom geo:asWKT ?gwkt }") | |
df <- SPARQL::SPARQL(endpoint,query)$results | |
sf_gage <- sf::st_as_sf(df,wkt="gage_geom",crs=4326) | |
sf_gage <- dplyr::select(sf_gage,-mainstem_geom) | |
sf_mainstem <- sf::st_as_sf(df[1,],wkt="mainstem_geom",crs=4326) | |
list <- list(sf_gage,sf_mainstem) | |
return(list) | |
} | |
hyperlink <- function(url){ | |
link <- paste0("<a href=", | |
gsub("<","",gsub(">","",url)), | |
">", | |
gsub("<","",gsub(">","",url)), | |
"</a>") | |
} | |
#call function | |
iowa <- find_mainstem_from_gage(gage_uri) | |
iowa[[1]]$gage <- hyperlink(iowa[[1]]$gage) | |
iowa[[1]]$mainstem <- NULL | |
iowa[[2]]$mainstem <- hyperlink(iowa[[2]]$mainstem) | |
iowa[[2]]$gage <- NULL | |
#map | |
mapview(iowa[1], layer.name="gages") + mapview(iowa[2],layer.name="mainstem") + mapview(start_gage,layer.name="Start Gage",col.regions="red") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment