python - 无法将几何图形转换为 geojson

标签 python flask geoalchemy2

我的问题是这样的。我正在为一些数据创建模型。

class Cables(Base):
    __tablename__ = 'cables'

    id = Column(Integer, nullable=False)
    route = Column(Geometry(geometry_type='LINESTRING', srid=4326), nullable=False)

现在,我想将这样的路线转换为 GeoJSON。

我尝试过的事情

@app.route("/api/cable/<int:id>", methods=['GET'])
def get_cable(id):
    cable = session.query(Cables).filter(Cables.id == id).first()
    return str(geoalchemy2.functions.ST_AsGeoJSON(cable.route))

返回ST_AsGeoJSON(ST_GeomFromEWKB(:ST_GeomFromEWKB_1))

如果我更改返回:

return geoalchemy2.functions.ST_AsGeoJSON(cable.route)

返回TypeError:'ST_AsGeoJSON'对象不可调用

return str(cable.route)

返回0102000020e610000002000000b34fd4d9bca351c032e14d5134c240c0d24f8055e0a351c0dedea9f4dcbf40c0 这表明我确实有一个几何对象。

return cable.route

返回类型错误:“WKBElement”对象不可调用

如果我打印路线类型,

print(type(cable.route))

返回

<class 'geoalchemy2.elements.WKBElement'>

我认为它应该返回此类的对象,而不是类本身。我现在很困惑,我不知道我现在应该做什么。

有什么建议吗?

最佳答案

调用 ST_AsGeoJSON 的正确方法似乎是在查询内部。 例如,

ruta = session.query(Cables.route.ST_AsGeoJSON()).filter(Cables.id == id).first()

我最终做的是安装一个新的库(shapely),以便读取十六进制字节串,然后将其转换为字典,因为字典可以以简单的方式转换为 json。

def ewkb_route_to_dict(self):
    """
    returns the cable's route as a dictionary.
    It uses shapely.wkb.loads. The first argument is the route as a bytestring,
    and the second one (True) is to tell loads that
    the input wkb will be represented as a hex string
    """
    return mapping(shapely.wkb.loads(str(self.route), True))

然后在我的 to string 方法中:

def __str__(self):
    d = dict()
    ...
    d["route"] = self.ewkb_route_to_dict()
    ...
    return dumps(d)

这将正确地将几何图形转换为 GeoJSON。

关于python - 无法将几何图形转换为 geojson,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41684512/

相关文章:

docker - 如何使用 docker 内的套接字将 nginx 套接字与 gunicorn 应用程序结合起来?

python - Geometry ('POINT' ) 列作为 str 对象返回

python - 比较/映射不同数据帧中的不同系列

python - 如何将初始数据附加到新的 wtforms FormField 作为默认值?

python - 使用 Windows 解析 Pandas 中的单个小数小时

python - 在 Flask 中使用 SQLAlchemy 创建数据库

python-3.x - Geoalchemy2 在给定坐标内查找一定距离内的位置

python - 迭代数据框并根据条件替换值

python - Pandas read_xml 将 "N/A"读取为 NaN