Skip to content

Instantly share code, notes, and snippets.

@pcarolan
Last active January 31, 2021 07:41
Show Gist options
  • Save pcarolan/332c9d838febdc5c38806d96aad8db87 to your computer and use it in GitHub Desktop.
Save pcarolan/332c9d838febdc5c38806d96aad8db87 to your computer and use it in GitHub Desktop.
Generate H3 hexgrid shapefiles
```python
# Imports
from h3 import h3
import folium
from shapely import geometry
import fiona
import geopandas as gpd
import descartes
# functions
def get_subindexes(h3_key):
return h3.h3_to_children(h3_key)
def flatten(indexes):
return [item for sublist in indexes for item in sublist]
def get_indexes_for_level(depth, current_level=0, indexes=h3.get_res0_indexes()):
print(f'Generating cells for depth: {depth}, current_level: {current_level}, idx_len: {len(indexes)}')
if depth == current_level:
return indexes
indexes = flatten([get_subindexes(index) for index in indexes])
current_level+=1
return get_indexes_for_level(depth, current_level, indexes)
def generate_shapefile(level):
indexes = get_indexes_for_level(level)
# Define Schema
schema = {
'geometry': 'Polygon',
'properties': {
'id': 'int',
'h3_key': 'str',
},
}
# Write to Shapefile
file_name = f'./shapefiles/h3_level_{level}.shp'
print(f'Writing cells:{len(indexes)}, level: {level}, file: \'{file_name}\'')
with fiona.open(file_name, 'w', 'ESRI Shapefile', schema) as c:
for id, h3_key in enumerate(indexes):
polygon = geometry.Polygon(h3.h3_to_geo_boundary(h3_key, True))
c.write({
'geometry': geometry.mapping(polygon),
'properties': {
'id': id,
'h3_key': h3_key
},
})
print(f'DONE')
# Run
level = 2
generate_shapefile(level)
shape=gpd.read_file(f'./shapefiles/h3_level_{level}.shp')
shape.plot(figsize=(30,30),cmap="Blues")
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment