Skip to content

Instantly share code, notes, and snippets.

@cboettig
Created February 4, 2025 23:28
Show Gist options
  • Save cboettig/74c9552f659d4882f4c2d7dcd8089b19 to your computer and use it in GitHub Desktop.
Save cboettig/74c9552f659d4882f4c2d7dcd8089b19 to your computer and use it in GitHub Desktop.
polygon-to-h3
# get the h0 hexes covering a polygon.
library(duckdbfs)
library(dplyr)
library(sf)
library(spData)
duckdbfs::load_h3()
duckdbfs::load_spatial()
tmp <- tempfile(fileext = ".fgb")
bounds <- spData::us_states |> dplyr::filter(NAME == "Arizona") |> st_transform(4326) |> write_sf(tmp, append = FALSE)
tmp2 <- tempfile(fileext = ".fgb")
world |> filter(iso_a2 == "US") |> write_sf(tmp2, append = FALSE)
subset <-
open_dataset(tmp2) |>
mutate(poly = array_extract(unnest(st_dump(geom)),"geom"),
hexid = h3_polygon_wkt_to_cells(poly,4L), # must be small enough?
hexid = unnest(hexid)
) |>
mutate(h0 = h3_h3_to_string( h3_cell_to_parent(hexid, 0L)),
hexid = h3_h3_to_string (hexid) ) |>
select(h0) |>
distinct() |>
pull(h0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment