在Python 3上使用PostGIS

2024-06-17 09:11:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Python 3,需要用postGIS扩展连接到postGre。 我打算使用psycopg2驱动程序。
这个PPyGIS是我找到的唯一扩展,但它在python 2.7而不是3.3.0上工作。
有人知道3.3.0的解决方案吗?


Tags: 驱动程序解决方案psycopg2postgispostgreppygis
3条回答

如果您对客户端(Python)上的几何体对象不感兴趣,那么psycopg2可以使用带有geometry accessors的本机数据类型或其他类似于GeoJSON的GIS获得最基本的信息。让服务器(PostgreSQL/PostGIS)来做这项艰苦的工作。

下面是一个随机示例,用于将GeoJSON返回到距关注点1公里内的形状:

import psycopg2
conn = psycopg2.connect(database='postgis', user='postgres')
curs = conn.cursor()

# Find the distance within 1 km of point-of-interest
poi = (-124.3, 53.2)  # longitude, latitude

# Table 'my_points' has a geography column 'geog'
curs.execute("""\
SELECT gid, ST_AsGeoJSON(geog), ST_Distance(geog, poi)
FROM my_points, (SELECT ST_MakePoint(%s, %s)::geography AS poi) AS f
WHERE ST_DWithin(geog, poi, 1000);""", poi)

for row in curs.fetchall():
    print(row)

既然有人问这个问题,Geopandas包就添加了

classmethod GeoDataFrame.from_postgis(sql, con, geom_col='geom', 
    crs=None, index_col=None, coerce_float=True, parse_dates=None, params=None)

它将从带有几何列的sql表中检索geodataframe

http://geopandas.org/reference.html#geopandas.GeoDataFrame.from_postgis

实际上,您可以使用ShapelyGDAL/OGR,但这两个库都有一长串依赖项。

如果你只有很少的用例,你也可以自己实现一个小的协议,基于超级光滑的pygeoif库,如下面的例子

from psycopg2.extensions import register_adapter, AsIs, adapt
from pygeoif.geometry import Point

def adapt_point(pt):
    return AsIs("ST_SetSRID(ST_MakePoint({}, {}), 4326)".format(adapt(pt.x), adapt(pt.y)))

register_adapter(Point, adapt_point)

相关问题 更多 >