to_shape()因ParseException而失败

时间:2014-12-30 11:32:54

标签: python shapely geoalchemy2 wkb

我一直在尝试使用GeoAlchemy2,我have some trouble with parsing its geom field

我试过use the built-in to_shape function on a WKB element

示例如下:

lake = Session.query(Lake).get(1)
polygon = to_shape(lake.geom)

我用过:

house = config.database.db_session.query(House)\
        .filter_by(house_id=1).first()
print "geom:", house.geom
01e90300009aea561e53634140ffb86b0da20a40400000000000000000

from geoalchemy2 import shape
print "to_shape:", shape.to_shape(house.geom)

to_shape:
Traceback (most recent call last):
  File "ranker_tester.py", line 40, in <module>
    print "to_shape:", shape.to_shape(house.geom)
  File ".../lib/python2.7/site-packages/GeoAlchemy2-0.2.4-py2.7.egg/geoalchemy2/shape.py", line 24, in to_shape
    return shapely.wkb.loads(bytes(element.data))
  File ".../lib/python2.7/site-packages/shapely/wkb.py", line 16, in loads
    return reader.read(data)
  File ".../lib/python2.7/site-packages/shapely/geos.py", line 361, in read
    raise ReadingError("Could not create geometry because of errors "
shapely.geos.ReadingError: Could not create geometry because of errors while reading input.

知道如何解析这个GeoAlchemy2 geom字段?数据库值有效。

1 个答案:

答案 0 :(得分:1)

我没有使用GeoAlchemy2,因此我无法评论它是如何生成它的WKB的,除非说它是与Shapely / GEOS使用的方言不同的方言。

您提供的WKB是OGC / ISO(使用PostGIS使用encode(ST_AsBinary(geom), 'hex')):

01e90300009aea561e53634140ffb86b0da20a40400000000000000000

这是WKT等价物(即ST_AsText(geom)):

POINT Z (34.7759740757367 32.0830704475393 0)

但是,Shapely和GEOS不支持更高维度的几何形状的OGC / ISO WKB。它仅支持为PostGIS(以及OGC / ISO规范之前的日期)指定的EWKB,它看起来像这样(即encode(ST_AsEWKB(geom), 'hex')):

01010000809aea561e53634140ffb86b0da20a40400000000000000000

所以这适用于Shapely,

from shapely.wkb import loads
pt = loads('01010000809aea561e53634140ffb86b0da20a40400000000000000000', hex=True)
pt.wkt  # 'POINT Z (34.77597407573667 32.08307044753928 0)'
pt.wkb_hex  # '01010000809AEA561E53634140FFB86B0DA20A40400000000000000000'

我不确定这会如何帮助您解决问题,但可能会对正在发生的事情表示煽动。如果您没有使用Z维度,您可以坚持使用2D几何图形,其中WKB对于OGC / ISO WKB和EWKB规范是相同的。