所以我遇到了这样一种情况:我有很多断开的线路,需要使用Shapely的LineMerge或Union或PostGIS STúu Union将它们合并在一起。
我现在的想法是使用Shapely将Linestrings导入为几何类型。合并它们或使用Shapely合并它们,然后导出回数据库中的结果表。
然而,PostGIS数据库中的几何类型只是一堆胡言乱语。就像。。。

01020000020e61000....

如何使用Shapely将其从数据库转换为Python几何类型,进行一些操作,然后将其导出回数据库?
目前这是我的代码,它只是从数据库中导入geom对象字符串,并抛出错误,因为它不是一个几何类型。
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.

最佳答案

Shapely already has libraries for this specific problem.
PostGIS将几何图形存储为十六进制值。使用Shapely的load s函数以hex=True的参数加载它。
明确地。。。

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

不要使用PostGIS ST_Union,因为您必须反复转储和加载才能正常工作。Shapely还配置了linemerge

10-08 13:19