将PostGIS表转换为Python中的Shapefile?


10

我想将PostGIS表转换为shapefile(不使用pgsql2shp)。

为了在shapefile中创建几何,我必须提供Xmin,Ymin和Xmax,Ymax,而我在PostGIS表中拥有的几何是不规则形状的(我可以使用边界框获得外部,但是其中包括比我最笨拙的区域多一些)。有什么方法可以完成任务?

我想以编程方式并使用Python进行操作。

Answers:


12

如果您想使用Python进行编程,那么GDAL / OGR可能是最好的方法。查看将表从PostgreSQL复制到SHP文件的示例示例代码。示例不是完美的,但是您可以轻松地对其进行修改以满足您的需求。

import os
os.environ['PATH'] = "c:\\Program Files\\GDAL\\bin" + ';' + os.environ['PATH']
os.environ['GDAL_DRIVER_PATH'] = "c:\\Program Files\\GDAL\\bin\\gdal\\plugins-optional"
os.environ['GDAL_DATA'] = "c:\\Program Files\\GDAL\\bin\\gdal-data"
import ogr

conn=ogr.Open("PG: host=192.168.5.3 dbname=some_database user=postgres password=xxxx")
if conn is None:
    print 'Could not open a database or GDAL is not correctly installed!'
    sys.exit(1)

output = "d:\\points.shp"

# Schema definition of SHP file
out_driver = ogr.GetDriverByName( 'ESRI Shapefile' )
out_ds = out_driver.CreateDataSource(output)
out_srs = None
out_layer = out_ds.CreateLayer("point", out_srs, ogr.wkbPoint)
fd = ogr.FieldDefn('name',ogr.OFTString)
out_layer.CreateField(fd)


layer = conn.GetLayerByName("point_data")
#layer = conn.ExecuteSQL(sql)

feat = layer.GetNextFeature()
while feat is not None:
    featDef = ogr.Feature(out_layer.GetLayerDefn())
    featDef.SetGeometry(feat.GetGeometryRef())
    featDef.SetField('name',feat.TITLE)
    out_layer.CreateFeature(featDef)
    feat.Destroy()
    feat = layer.GetNextFeature()

conn.Destroy()
out_ds.Destroy()

如果您的编程环境是Windows,则可以从此处下载GDAL / OGR 。您可以在此处找到一些很好的起始材料。希望能帮助到你。


1

我可以建议您看一下GDAL / OGR库:http ://www.gdal.org/ogr/index.html

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.