uber / h3-py

Python bindings for H3, a hierarchical hexagonal geospatial indexing system
https://uber.github.io/h3-py
Apache License 2.0
815 stars 130 forks source link

Generate hexagons over areas not entirely within a polygon? #379

Closed marklit closed 4 months ago

marklit commented 4 months ago

I want to generate H3s for the coastal areas as well as anything inland. With h3.LatLngPoly it only wants to generate hexagons that are entirely in land and miss areas like Miami for example. Any idea how I could do this?

qgis-bin_0RQJmFLOPZ

Here's the code that I have atm:

$ wget https://raw.githubusercontent.com/scdoshi/us-geojson/master/geojson/nation/US.geojson
import geopandas as gpd
import h3

print(h3.versions()) # {'c': '4.0.0', 'python': '4.0.0b5'}

usa = gpd.read_file('US.geojson')
polygons = list(list(x.geoms) for x in usa.geometry)[0]

polygons.sort(key=lambda x: x.area)
coords = polygons[-1].exterior.coords[:]
coords = list(c[:2][::-1] for c in coords)

poly = h3.LatLngPoly(coords)

h3_list = set(h3.h3shape_to_cells(poly, res=3))
grim7reaper commented 4 months ago

I think it's now possible to do that with the H3 C library, but it's not yet exposed in h3-py IIUC.

Meanwhile you could try h3ronpy, with ContainmentMode=IntersectsBoundary (or Cover) it should do the trick. Cf. example here.

If it's a one-shot thing, you could also use h3o-cli:

h3o-cli geomToCells -r 3 -m intersects-boundary  < US.geojson | h3o-cli cellToPolygon > H3-coverage.geojson
Screenshot 2024-06-03 at 13 13 29
marklit commented 4 months ago

Thanks for that.