【问题标题】:Importing a PostGIS geometry type into Python as a geometry type from Shapely?将 PostGIS 几何类型作为 Shapely 的几何类型导入 Python?
【发布时间】:2017-10-18 02:16:39
【问题描述】:

所以我遇到了这样一种情况,我有大量断开的路线的线串,我需要使用 Shapely 的 LineMerge 或 Union OR PostGIS ST_Union 将它们联合在一起。

我现在的想法是使用 Shapely 将 Linestrings 导入为几何类型。使用 Shapely 合并或合并它们,然后导出回数据库中的结果表。

然而,PostGIS 数据库中的几何类型只是一堆乱码。喜欢...

01020000020e61000....

如何使用 Shapely 将其从数据库转换为 Python 几何类型,进行一些操作,然后将其导出回数据库?

目前这是我的代码,它现在只是从数据库中导入该几何对象字符串并抛出错误,因为它不是几何类型。

def create_shortest_route_geom(shortest_routes):
    conn = connect_to_database()
    cur = conn.cursor()
    shortest_route_geoms = []
    for route in shortest_routes:
        source = str(int(route[1]))
        target = str(int(route[2]))
        query = 'SELECT the_geom FROM public.ways WHERE target_osm = ' + target + ' AND source_osm = ' + source + ' OR target_osm = ' + source + ' AND source_osm = ' + target + ';'
        cur.execute(query)
        total_geom = cur.fetchone()
        for index, node in enumerate(route):
            try:
                source = str(int(node))
                target = str(int(route[index + 1]))
                query = 'SELECT the_geom FROM public.ways WHERE target_osm = ' + target + ' AND source_osm = ' + source + ' OR target_osm = ' + source + ' AND source_osm = ' + target + ';'
                cur.execute(query)
                geom = cur.fetchone()
                query = "SELECT ST_Union("+str(geom[0])+","+str(total_geom[0])+")"
                cur.execute(query)
                total_geom = cur.fetchone()
            except IndexError:
                print "Last element"
        shortest_route_geoms.insert(total_geom)
    return shortest_route_geoms

编辑:I may have found my answer here, looking more into it and will update my question with an answer if I figure this out.

【问题讨论】:

  • 请使用占位符代替将字符串连接到 SQL 查询的值。使代码更具可读性,消除了手动“处理”引用的需要,并降低了注入的风险。

标签: python postgresql gis postgis shapely


【解决方案1】:

Shapely already has libraries for this specific problem.

PostGIS 将几何图形存储为 HEX 值。使用 Shapely 的 load 函数加载 this,参数为 hex=True。

具体...

geom = shapely.wkb.loads(hex_geom[0], hex=True)

不要使用 PostGIS ST_Union,因为您必须一遍又一遍地转储和加载才能使其正常工作。 Shapely 也配置了 linemerge

【讨论】:

    猜你喜欢
    • 2019-11-04
    • 1970-01-01
    • 2011-10-14
    • 2023-01-11
    • 1970-01-01
    • 1970-01-01
    • 2021-06-28
    • 2014-10-06
    • 2011-01-02
    相关资源
    最近更新 更多