建设道路十字路口时出错

时间:2016-05-25 12:02:03

标签: python postgresql postgis shapely

我试图将原始道路数据分成几个部分。首先,我创建了road_segments表。然后我使用匀称将道路表的内容转换为一系列连接的路段。

对于每条道路,我首先将道路的名称和几何图形加载到内存中。

此处的代码正常工作。

我得到了道路的LineString几何体,我想在它接触或穿过另一条道路的每个点处分开。为此,我尝试为这条道路建立一个交叉道路清单。

 crossroads = []
 cursor.execute("SELECT ST_AsText(centerline) FROM ROADS" +
                   "WHERE ST_Touches(roads.centerline, " +
                   "ST_GeomFromText(%s)) OR ST_Crosses(" +
                   "roads.centerline, ST_GeomFromText(%s))",
                   (wkt, wkt))
  for row in cursor:
        crossroad = shapely.wkt.loads(row[0])
        crossroads.append(crossroad)

但是下面的错误来了:

---------------------------------------------------------------------------
ProgrammingError                          Traceback (most recent call last)
<ipython-input-9-0d71c4db883b> in <module>()
      4                    "ST_GeomFromText(%s)) OR ST_Crosses(" +
      5                    "roads.centerline, ST_GeomFromText(%s))",
----> 6                    (wkt, wkt))

ProgrammingError: syntax error at or near "."
LINE 1: ...sText(centerline) FROM ROADSWHERE ST_Touches(roads.centerlin...

当我编辑代码如下:

crossroads = []
cursor.execute("SELECT ST_AsText(centerline) FROM ROADS WHERE ST_Touches(roads.centerline, " +
                   "ST_GeomFromText(%s)) OR ST_Crosses(" +
                   "roads.centerline, ST_GeomFromText(%s))",
                   (wkt, wkt))
for row in cursor:
    crossroad = shapely.wkt.loads(row[0])
    crossroads.append(crossroad)

以下错误:

---------------------------------------------------------------------------
InternalError                             Traceback (most recent call last)
<ipython-input-5-b50bc9a8488c> in <module>()
      3                    "ST_GeomFromText(%s)) OR ST_Crosses(" +
      4                    "roads.centerline, ST_GeomFromText(%s))",
----> 5                    (wkt, wkt))
      6 for row in cursor:
      7     crossroad = shapely.wkt.loads(row[0])

InternalError: current transaction is aborted, commands ignored until end of transaction block

1 个答案:

答案 0 :(得分:1)

第一个错误是因为“ROADSWHERE”之间没有空格,第二个错误是因为需要回滚事务,即conn.rollback()

首先,WKB是一种在PostGIS和Shapely之间传输几何体的更快速无损方式。您可以从具有.wkb_hex属性的匀称几何图形和PostGIS中获取此特征,而无需执行任何特殊操作。其次,我发现最好使用三引号编写SQL表达式,如下所示:

from shapely import wkb
cursor.execute("""\
SELECT centerline FROM ROADS
WHERE ST_Touches(roads.centerline, %(geom)s)
   OR ST_Crosses(roads.centerline, %(geom)s;
""", {'geom': geom.wkb_hex})
for row in cursor:
    crossroad = wkb.loads(row[0], hex=True)
    crossroads.append(crossroad)

最后,我不确定它是否有帮助,但为了更好地理解谓词运算符如“触摸”和“十字架”如何工作,您可能希望看到DE-9IM。您可以使用ST_Relate创建自定义谓词,而不是调用两个不同的谓词。