Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

clean up geojson input #151

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 32 additions & 13 deletions driptorch/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,32 @@ def to_wgs84(cls, geometry: Union[BaseGeometry, dict], src_epsg: int) -> Union[B
return projector.forward(geometry)


def find_dicts_with_keys(d, key1: str = "type", key2: str = "coordinates"):
"""Recursively traverse the dictionary and return a list of all children
dictionaries that contain the specific keys.

Wrote with intention to effectively parse geojson dicts

Args:
d (dict): input dictionary
key1 (str, optional): first key to search. Defaults to "type".
key2 (str, optional): second key to search. Defaults to "coordinates".

Returns:
list: list of found dicts containing key1 and key2
"""
result = []
if isinstance(d, dict):
if key1 in d and key2 in d:
result.append(d)
for v in d.values():
result += find_dicts_with_keys(v, key1, key2)
elif isinstance(d, list):
for i in d:
result += find_dicts_with_keys(i, key1, key2)
return result


def read_geojson_polygon(geojson: dict) -> Polygon:
"""Parse a GeoJSON to a shapely Polygon

Expand All @@ -163,24 +189,17 @@ def read_geojson_polygon(geojson: dict) -> Polygon:
Shapely polygon geometry
"""

geojson = {
"geometry": find_dicts_with_keys(geojson)[0]
}

# If the geojson is a feature collection then we loop over the features
# and find the first instance of a polygon geometry type
if geojson['type'] == 'FeatureCollection':
for feature in geojson['features']:
if feature['geometry']['type'].lower() == 'polygon':
geometry = shape(feature['geometry'])
break

# Maybe it's just the geometry?
elif geojson['type'].lower() == 'Polygon':
geometry = shape(geojson)

# Fix your shit, we're not gonna to keep trying to guess
if geojson['geometry']['type'].lower() == "polygon":
return shape(geojson)
else:
raise GeojsonError(GeojsonError.read_error)

return geometry


def write_geojson(geometries: list[BaseGeometry], src_epsg: int, dst_epsg: int = 4326, properties={},
style={}, elapsed_time=None) -> dict:
Expand Down