无法将几何体转换为geojson

2024-05-23 19:03:18 发布

您现在位置:Python中文网/ 问答频道 /正文

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

class Cables(Base):
    __tablename__ = 'cables'

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

现在,我想将这样一个路由转换为GeoJSON。在

我试过的东西

^{pr2}$

返回ST_AsGeoJSON(ST_GeomFromEWKB(:ST_GeomFromEWKB_1))

如果我更改回报:

return geoalchemy2.functions.ST_AsGeoJSON(cable.route)

返回TypeError: 'ST_AsGeoJSON' object is not callable

return str(cable.route)

返回0102000020e610000002000000b34fd4d9bca351c032e14d5134c240c0d24f8055e0a351c0dedea9f4dcbf40c0 这意味着我有一个几何对象。在

return cable.route

返回TypeError: 'WKBElement' object is not callable

如果我打印路线类型

print(type(cable.route))

退货

<class 'geoalchemy2.elements.WKBElement'>

我认为它应该返回这样一个类的对象,而不是类本身。我现在很困惑,不知道该怎么办。在

有什么建议吗?在


Tags: falsereturnobjectistypecolumngeoalchemy2route
3条回答

In the docs,PostGIS帮助您:

ST_AsGeoJSON only builds geometry. You need to build the rest of Feature from your Postgres table yourself

实际上,尝试将ST_AsGeoJSON的输出发送到传单层将失败,因为它不是有效的Feature。虽然文档提供了25行PostGIS代码,但将其与SQLAlchemy一起使用是不吸引人的。我发现最简单的方法是使用一个小的python库^{}。在

$ pip install shapely-geojson

然后在你的代码中:

^{pr2}$

请注意,GeoJSON标准在2016年进行了更改,以实施right hand rule。根据数据中直线或多边形的结构,以及接收软件的挑剔程度,您可能需要使用^{}来更改点的顺序。在

我知道这个帖子已经过时了,但是对于那些仍然有这个问题的人,我的解决方法如下:

import ast
from flask.json import jsonify
from sqlalchemy import func

@app.route("/api/cable/<int:id>", methods=['GET'])
def get_cable(id):
    geom = session.query(func.ST_AsGeoJSON(Cables.route)).filter(Cables.id == id).scalar()
    # The code below makes a geojson with CRS.
    # See http://www.postgis.org/docs/ST_AsGeoJSON.html for more details.
    #geom = session.query(func.ST_AsGeoJSON(Cables.route,15,2)).filter(Cables.id == id).scalar()
    return jsonify(ast.literal_eval(geom))

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

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

最后我要做的是安装一个新的库(shapely),以便读取hex bytestring,然后将其转换为字典,因为字典可以很容易地转换为json。在

^{pr2}$

然后在我的to string方法中:

^{3}$

这将正确地将几何体转换为GeoJSON。在

相关问题 更多 >