2017-10-18 287 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