here.geopandas_adapter.utils.geo

Source code for here.geopandas_adapter.utils.geo

Copyright (C) 2019-2022 HERE Global B.V. and its affiliate(s).

All rights reserved.

This software and other materials contain proprietary information

controlled by HERE and are protected by applicable copyright legislation.

Any use and utilization of this software and other materials and

disclosure to any third parties is conditional upon having a separate

agreement with HERE for the access, use, utilization or disclosure of this

software. In the absence of such agreement, the use of the software is not

allowed.

"""
Utilities to convert geometries for use with GeoPandas
"""
import json
from typing import Optional

import shapely.wkt
from geojson.mapping import GEO_INTERFACE_MARKER
from here.platform.utils.geo import (
is_geojson_geometry,
is_nonstandard_geometry,
nonstandard_to_geometry,
)
from shapely.geometry.base import BaseGeometry

[docs]
def to_geometry(x) -> Optional[BaseGeometry]:
"""
Convert an object to a shapely geometry for use with geopandas.

This is used to convert columns of a variety of types to geopandas' geometry type.

Supported formats::

  • None passed through as None
  • str containing a geometry in GeoJSON format
  • str containing a geometry in WKT format
  • object with __geo_interface__
  • a Mapping in the format of a GeoJSON geometry
  • a BaseGeometry, returned unchanged
  • an object in a supported, non-standard format. For more information
    please see here.platform.utils.geo.is_nonstandard_geometry

:param x: the object to convert
:return: the object converted to a shapely geometry
:raises ValueError: in case the object cannot be converted
"""
if x is None:
return None
elif isinstance(x, BaseGeometry):
return x
elif isinstance(x, str) and x.startswith("{"):
return shapely.geometry.shape(json.loads(x))
elif isinstance(x, str):
return shapely.wkt.loads(x)
elif hasattr(x, GEO_INTERFACE_MARKER):
return shapely.geometry.shape(x)
elif is_geojson_geometry(x):
return shapely.geometry.shape(x)
elif is_nonstandard_geometry(x):
return shapely.geometry.shape(nonstandard_to_geometry(x))
else:
raise ValueError(f"Cannot convert object of type {type(x)} to geometry")