2017-10-18 278 views
0

所以我有一种情况,我有一大堆拆散路线的Linestrings,我需要使用Shapely的LineMerge或Union或PostGIS ST_Union将它们联合在一起。从Shapely将PostGIS几何类型作为几何类型导入Python?

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

但是,PostGIS数据库中的几何类型只是一堆乱码。像...

01020000020e61000.... 

我如何使用匀称数据库为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.

+0

而不是字符串连接到SQL查询值请使用占位符。一般来说,使代码更具可读性,消除手动“处理”引用的需要,并减少注入风险。 –

回答

1

Shapely already has libraries for this specific problem.

PostGIS的存储的几何形状为十六进制值。使用Shapely的加载函数以十六进制= True的参数加载它。

具体...

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

不要使用PostGIS的ST_Union,因为你必须转储和装载一遍又一遍这个工作。 Shapely也配置了linemerge