h3-py icon indicating copy to clipboard operation
h3-py copied to clipboard

h3shape_to_cells | reversed coordinates return empty list

Open fhk opened this issue 9 months ago • 1 comments

When reading data with Geopandas the coords are flipped.

This does not give any errors and just gives back empty results.

Repro

    usa = gpd.read_file('https://raw.githubusercontent.com/scdoshi/us-geojson/master/geojson/nation/US.geojson')
    usa = list(usa.geometry.iloc[0].geoms)[0]
    coords = list(c[:2] for c in usa.exterior.coords[:])

    poly = h3.H3Poly(coords)
    print(poly)

    print(h3.h3shape_to_cells(poly, res=7))

This works when you reverse the coords

    usa = gpd.read_file('https://raw.githubusercontent.com/scdoshi/us-geojson/master/geojson/nation/US.geojson')
    usa = list(usa.geometry.iloc[0].geoms)[0]
    coords = list(c[:2][::-1] for c in usa.exterior.coords[:])

    poly = h3.H3Poly(coords)
    print(poly)

    print(h3.h3shape_to_cells(poly, res=7))

fhk avatar May 09 '24 01:05 fhk

Thanks for the issue! Feedback like this is super helpful for me to think through pain points in the API and how we can smooth it out.

Honestly, I was hoping for more of these before releasing the final v4.0. So if you have any more, please do keep them coming!

I'll take a look at this and #365

ajfriend avatar May 09 '24 15:05 ajfriend

I think the main issue here is that we don't handle the z-coordinate if it is present: #368

Also, you're having to reverse the coordinates because GeoPandas and GeoJSON use lng/lat coordinate order, while H3 is expecting lat/lng coordinate order. But ideally, we should just handle that translation automatically for you with functions like h3.geo_to_h3shape().

Once we implement #368, your code should be just:

usa = gpd.read_file('https://raw.githubusercontent.com/scdoshi/us-geojson/master/geojson/nation/US.geojson')
usa = usa.geometry[0]
shape = h3.geo_to_h3shape(usa)

However, in the meantime until #368, you can remove the z coordinate manually:

usa = gpd.read_file('https://raw.githubusercontent.com/scdoshi/us-geojson/master/geojson/nation/US.geojson')
usa = usa.geometry[0]

from shapely.ops import transform
def to_2d(x,y,z):
    return x,y
usa = transform(to_2d, usa)

shape = h3.geo_to_h3shape(usa)

ajfriend avatar May 14 '24 15:05 ajfriend

Also, see the comments in https://gist.github.com/rmania/8c88377a5c902dfbc134795a7af538d8 for some potentially faster methods using WKT.

ajfriend avatar May 14 '24 15:05 ajfriend

This should be fixed with https://github.com/uber/h3-py/releases/tag/v4.0.0b5, so I'll close this. Please let me know if you have any issues!

ajfriend avatar May 19 '24 18:05 ajfriend