I am trying to take a geojson file of points and convert it to H3 hexagons in my Python script. In JavaScript, there is a separate package called geojson2h3, but the Python h3 module has a method called `.geo_to_h3' that I am trying to utilize. It seems to take 3 arguments: a lat(X), a long(Y), and a resolution level. I have pulled in my GeoJSON file and have a JSON object like this:

{"crs": {"properties": {"name": "EPSG:4326"}, "type": "name"}, 
     "features": [
       {"geometry": {"coordinates": [-75.330278, 39.643889], "type": "Point"}, 
        "id": 0, "properties": 
           {"FID": 0, "Gauge_Name": "Salem River At Woodstown Nj", "Gauge_No": "01482500", 
            "State": "NJ", "X": 39.643889, "Y": -75.330278}, "type": "Feature"}, 
       {"geometry": {"coordinates": [-75.255556, 39.4725], "type": "Point"},

I can pull out coordinates of the individual features, but its messy and doesn't seem efficient:

import h3
import geojson
import os
import pandas
import numpy as np
import geopandas as gpd

dc_json_dir = r"C:\Projects\H3_Uber_Hexagon\data"
usgs_gauges = "riv_gauge_points.json"
gauge_path = os.path.join(dc_json_dir, usgs_gauges)

with open(gauge_path) as f:
    gj = geojson.load(f)
features = gj['features'][0]

x = features.geometry.coordinates[0]
y = features.geometry.coordinates[1]
level = 7

hexagon_test = h3.geo_to_h3(x, y, level)

So, it returns the H3 spatial index, but I still need to add it to the GeoJSON object or an object that I can render as a hexagon later. I can also put the geojson into a dataframe and maybe add the data from the X, Y columns:

def hex_indexer(row):
  x = row.X
  y = row.Y
  level = 10
  hex_val = h3.geo_to_h3(x, y, level)
  return hex_val

gauge_df = gpd.read_file(gauge_path)
gauge_df['H3_Index'] = gauge_df.apply(hex_indexer, axis=1)

    FID State  Gauge_Name      X          Y         Gauge_No    geometry                    H3_Index
  0   0 NJ     Salem River  39.643889  -75.330278   01482500    POINT(-75.33028 39.64389)   8a2aaca5132ffff
  1   1 NJ  Cohansey River  39.472500   -75.255556  01412800    POINT (-75.25556 39.47250)  8a2aadc34847fff

While this seems to work to create the h3 index, something doesn't seem to be right. Is there a better way to do this and get the data in a format that can be rendered using Python?

  • 1
    just simply add a new key/value in the existing "properties" element called "h3-index' ... a hexagon can be created on the fly with the h3 lib.
    – Jeryl Cook
    Mar 17, 2021 at 21:04


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.