get centroid latitude and longitude of h3 hexagon

Question:

I know ho to get h3 hexagon ids for various resolutions and add them to a pandas dataframe containing latitudes and longitudes. Is it possible to get the centroid latitude and longitude of each h3 hexagon given its id? I saw function but do not know how to use it in this context cell_to_latlng. Any pointers would be very much appreciated. thanks.

PS:

import h3
dir(h3)

does not show cell_to_lat_lng btw?!

This does not work:

from h3 import h3

h3.cell_to_lat_lng('88396c0331fffff')

I get:

AttributeError: module 'h3.api.basic_str' has no attribute 'cell_to_lat_lng'
Asked By: cs0815

||

Answers:

you can first create a new column in your pandas dataframe to hold the centroid latitude and longitude values. Then, for each row in the dataframe, you can use the cell_to_lat_lng function to convert the hexagon ID to its centroid latitude and longitude, and store the result in the corresponding row of the new columns.

E.G

import h3

# create new columns to hold centroid latitude and longitude
df['centroid_lat'] = 0.0
df['centroid_lng'] = 0.0

# iterate over rows in dataframe and compute centroid for each hexagon
for index, row in df.iterrows():
    hex_id = row['hex_id']
    lat, lng = h3.cell_to_lat_lng(hex_id)
    df.at[index, 'centroid_lat'] = lat
    df.at[index, 'centroid_lng'] = lng
Answered By: Salim Aljayousi

There’s currently a discrepancy between the docs and the released version of the h3-py library – the docs are for v4, but the released version is still v3 (v4 is in beta). In H3v3, the function you want is called h3_to_geo(hex_id).

Answered By: nrabinowitz
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.