问题描述
因此,我遇到了很多路线断开的线串的情况,需要使用Shapely的LineMerge或Union OR PostGIS ST_Union将它们组合在一起.
So I have a situation where I have a ton of Linestrings of a broken up route, where I need to Union them together using Shapely's LineMerge or Union OR PostGIS ST_Union.
我现在的想法是使用Shapely将线串导入为几何类型.合并它们或使用Shapely合并它们,然后导出回到数据库中的结果表.
My idea right now is to use Shapely to import the Linestrings as Geometry types. Union them or merge them using Shapely, and then export back to a results table in the database.
但是,PostGIS数据库中的几何类型只是一堆乱码.喜欢...
However, the geometry type in the PostGIS database is just a bunch of gibberish. Like...
01020000020e61000....
如何使用Shapely将其从数据库转换为Python几何类型,进行一些操作,然后将其导出回数据库?
How can I translate this from the database to a Python geometry type using Shapely, do some manipulations, and then export it back to a database?
当前这是我的代码,它只是立即从数据库中导入该geom对象字符串,并因为它不是Geometry类型而引发错误.
Currently this is my code, its just importing that geom object string from the database right now and throwing errors because it isn't a Geometry type.
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
我可能在这里找到了我的答案,对其进行了深入研究,并将更新我的问题如果我想出了答案,就会给出答案.
推荐答案
PostGIS将几何存储为十六进制值.使用Shapely的loads函数以参数hex = True加载它.
PostGIS stores the geometries as HEX values. Use Shapely's loads function to load this with the parameter of hex=True.
特别是...
geom = shapely.wkb.loads(hex_geom[0], hex=True)
请勿使用PostGIS ST_Union,因为您必须一遍又一遍地进行转储和加载才能正常工作. Shapely也使用 linemerge
Don't use PostGIS ST_Union, cause you have to dump and load over and over for this to work. Shapely has that configured as well with linemerge
这篇关于将PostGIS几何类型从Shapely中导入为Python的几何类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!