Introduction
The H3 geospatial indexing system by Uber assigns a unique hexadecimal string (called an H3 index) to every hexagon cell on the globe. Often, you’ll want to convert these indices back into latitude and longitude—either for visualization or for spatial analysis.
Install the H3 Python Library
Install the latest version of the official h3
library:
Version Check
There are two versions of the H3 Python library in the wild. To see which version of the H3 library you're using:
- If
Version >= 4.0.0
: use cell_to_latlng()
and cell_to_boundary()
- If
Version < 4.0.0
: use h3_to_geo()
and h3_to_geo_boundary()
Convert H3 Index to Lat/Lon
Using the New API (h3 >= 4.0.0
)
| import h3
# Example H3 index
h3_index = '8928308280fffff'
# Convert to (lat, lon)
lat, lon = h3.cell_to_latlng(h3_index)
print(f"Latitude: {lat}, Longitude: {lon}")
|
Output
| Latitude: 37.776702349435695, Longitude: -122.41845932318309
|
Using the Older API (pre-4.0.0)
Code:
| import h3
h3_index = '8928308280fffff'
lat, lon = h3.h3_to_geo(h3_index)
print(f"Latitude: {lat}, Longitude: {lon}")
|
Get H3 Cell Boundary (Polygon Vertices)
If you want the boundary coordinates of the H3 cell (for plotting as a hexagon):
New API:
| import h3
boundary = h3.cell_to_boundary(h3_index)
for lat, lon in boundary:
print(f"Lat: {lat}, Lon: {lon}")
|
Output
| Lat: 37.775197782893386, Lon: -122.41719971841658
Lat: 37.77688044840227, Lon: -122.41612835779266
Lat: 37.778385004930925, Lon: -122.41738797617619
Lat: 37.77820687262237, Lon: -122.41971895414808
Lat: 37.776524206993216, Lon: -122.42079024541879
Lat: 37.775019673792606, Lon: -122.41953062807342
|
Old API:
| import h3
boundary = h3.h3_to_geo_boundary(h3_index, geo_json=True)
for lat, lon in boundary:
print(f"Lat: {lat}, Lon: {lon}")
|
Batch Convert H3 Indices to Lat/Lon in a List or DataFrame
With a list:
| h3_indices = ['8928308280fffff', '8928308280bffff', '89283082807ffff']
latlon_list = [h3.cell_to_latlng(h) for h in h3_indices]
|
Output
| [(37.776702349435695, -122.41845932318309),
(37.7753758485188, -122.41486876560982),
(37.77484152121918, -122.42186149457379)]
|
With a pandas DataFrame:
| import pandas as pd
import h3
df = pd.DataFrame({'h3_index': ['8928308280fffff', '8928308280bffff']})
# Add columns for lat/lon
df[['lat', 'lon']] = df['h3_index'].apply(lambda h: pd.Series(h3.cell_to_latlng(h)))
|
Output
| h3_index lat lon
0 8928308280fffff 37.776702 -122.418459
1 8928308280bffff 37.775376 -122.414869
|
Summary
Task |
New API (>= 4.0.0 ) |
Old API (legacy) |
Get center lat/lon |
cell_to_latlng() |
h3_to_geo() |
Get hex boundary |
cell_to_boundary() |
h3_to_geo_boundary() |