Skip to content

Commit 2acb0ab

Browse files
committed
Handle generic __geo_interface__ objects via fiona and geopandas
Hacky attempt to handle non-geopandas objects (e.g. shapely.geometry) that have a __geo_interface__ dictionary property associated with it. Still assumes that geopandas is installed (along with fiona), so not a perfect solution. Also added another test with different geometry types.
1 parent 21b3160 commit 2acb0ab

File tree

2 files changed

+46
-2
lines changed

2 files changed

+46
-2
lines changed

pygmt/helpers/tempfile.py

+28-2
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,32 @@ def tempfile_from_geojson(geojson):
127127
"""
128128
with GMTTempFile(suffix=".gmt") as tmpfile:
129129
os.remove(tmpfile.name) # ensure file is deleted first
130-
# Using geopandas.to_file to directly export to OGR_GMT format
131-
geojson.to_file(filename=tmpfile.name, driver="OGR_GMT", mode="w")
130+
ogrgmt_kwargs = dict(filename=tmpfile.name, driver="OGR_GMT", mode="w")
131+
try:
132+
# Using geopandas.to_file to directly export to OGR_GMT format
133+
geojson.to_file(**ogrgmt_kwargs)
134+
except AttributeError:
135+
# pylint: disable=import-outside-toplevel
136+
# Other 'geo' formats which implement __geo_interface__
137+
import json
138+
139+
import fiona
140+
import geopandas as gpd
141+
142+
with fiona.Env():
143+
jsontext = json.dumps(geojson.__geo_interface__)
144+
# Do Input/Output via Fiona virtual memory
145+
with fiona.io.MemoryFile(file_or_bytes=jsontext.encode()) as memfile:
146+
geoseries = gpd.GeoSeries.from_file(filename=memfile)
147+
geoseries.to_file(**ogrgmt_kwargs)
148+
149+
# with memfile.open(driver="GeoJSON") as collection:
150+
# # Get schema from GeoJSON
151+
# schema = collection.schema
152+
# # Write to temporary OGR_GMT format file
153+
# with fiona.open(
154+
# fp=tmpfile.name, mode="w", driver="OGR_GMT", schema=schema
155+
# ) as ogrgmtfile:
156+
# ogrgmtfile.write(geojson.__geo_interface__)
157+
132158
yield tmpfile.name

pygmt/tests/test_geopandas.py

+18
Original file line numberDiff line numberDiff line change
@@ -46,3 +46,21 @@ def test_geopandas_info_geodataframe(gdf):
4646
"""
4747
output = info(table=gdf, per_column=True)
4848
npt.assert_allclose(actual=output, desired=[0.0, 35.0, 0.0, 20.0])
49+
50+
51+
@pytest.mark.parametrize(
52+
"geomtype,desired",
53+
[
54+
("multipolygon", [0.0, 35.0, 0.0, 20.0]),
55+
("polygon", [20.0, 23.0, 10.0, 14.0]),
56+
("linestring", [20.0, 30.0, 15.0, 15.0]),
57+
],
58+
)
59+
def test_geopandas_info_shapely(gdf, geomtype, desired):
60+
"""
61+
Check that info can return the bounding box region from a shapely.geometry
62+
object that has a __geo_interface__ property.
63+
"""
64+
geom = gdf.loc[geomtype].geometry
65+
output = info(table=geom, per_column=True)
66+
npt.assert_allclose(actual=output, desired=desired)

0 commit comments

Comments
 (0)