【发布时间】: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
【问题讨论】:
-
请使用占位符代替将字符串连接到 SQL 查询的值。使代码更具可读性,消除了手动“处理”引用的需要,并降低了注入的风险。
标签: python postgresql gis postgis shapely