Skip to content

Instantly share code, notes, and snippets.

@cboettig
Created January 5, 2025 00:13
Show Gist options
  • Save cboettig/89798ae0c898adacc01b6a8136fc57a0 to your computer and use it in GitHub Desktop.
Save cboettig/89798ae0c898adacc01b6a8136fc57a0 to your computer and use it in GitHub Desktop.
Dynamically filter pmtiles and plot with maplibre in R
library(mapgl)
library(dplyr)
library(duckdbfs)
# This test file demonstrates that given a SQL query on the parquet version
# of the data, we can identify all the features included in the response and
# construct a maplibre filter that filters the corresponding features in
# the pmtiles vesion.
pmtiles <- "https://data.source.coop/cboettig/social-vulnerability/svi2020_us_tract.pmtiles"
parquet <- "https://data.source.coop/cboettig/social-vulnerability/svi2020_us_tract.parquet"
svi <- open_dataset(parquet, tblname = "svi")
response = list(query =
"SELECT STATE, AVG(RPL_THEMES) as avg_social_vulnerability
FROM svi GROUP BY STATE, ORDER BY avg_social_vulnerability
DESC LIMIT 1")
con <- duckdbfs::cached_connection()
df <- DBI::dbGetQuery(con, response$query)
filter_column <- function(full_data, filtered_data, id_col) {
values <- full_data |>
inner_join(filtered_data, copy=TRUE) |>
pull(id_col)
# maplibre syntax for the filter of PMTiles
list("in", list("get", id_col), list("literal", values))
}
maplibre(center = c(-102.9, 41.3), zoom = 3) |>
add_fill_layer(
id = "svi_layer",
source = list(type = "vector", url = paste0("pmtiles://", pmtiles)),
source_layer = "SVI2000_US_tract",
filter = filter_column(svi, df, "FIPS"),
fill_opacity = 0.5,
fill_color = interpolate(column = "RPL_THEMES",
values = c(0, 1),
stops = c("lightblue", "darkblue"),
na_color = "lightgrey")
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment