跳转至

投影

创建投影

from osgeo import osr
spatialRef = osr.SpatialReference()
spatialRef.ImportFromEPSG(4326) #WGS84

重投影

from osgeo import ogr
from osgeo import osr

source = osr.SpatialReference()
source.ImportFromEPSG(2927)

target = osr.SpatialReference()
target.ImportFromEPSG(4326)

transform = osr.CoordinateTransformation(source, target)

point = ogr.CreateGeometryFromWkt("POINT (1120351.57 741921.42)")
point.Transform(transform)

print (point.ExportToWkt())

获取投影

from osgeo import ogr, osr
driver = ogr.GetDriverByName('ESRI Shapefile')
dataset = driver.Open(r'./data/test.shp')

# 图层
layer = dataset.GetLayer()
spatialRef = layer.GetSpatialRef()
# 几何
feature = layer.GetNextFeature()
geom = feature.GetGeometryRef()
spatialRef = geom.GetSpatialReference()

重投影图层

from osgeo import ogr, osr
import os

driver = ogr.GetDriverByName('ESRI Shapefile')

# 输入空间参考
inSpatialRef = osr.SpatialReference()
inSpatialRef.ImportFromEPSG(2927)

# 输出空间参考
outSpatialRef = osr.SpatialReference()
outSpatialRef.ImportFromEPSG(4326)

# 创建坐标转换
coordTrans = osr.CoordinateTransformation(inSpatialRef, outSpatialRef)

# 输入图层
inDataSet = driver.Open(r'./data/test.shp')
inLayer = inDataSet.GetLayer()

# 创建输出图层
outputShapefile = r'./data/test_4326.shp'
if os.path.exists(outputShapefile):
    driver.DeleteDataSource(outputShapefile)
outDataSet = driver.CreateDataSource(outputShapefile)
outLayer = outDataSet.CreateLayer(
    "test_4326", 
    geom_type=ogr.wkbMultiPolygon,
    srs=outSpatialRef # 输出prj文件
)

# 添加字段
inLayerDefn = inLayer.GetLayerDefn()
for i in range(0, inLayerDefn.GetFieldCount()):
    fieldDefn = inLayerDefn.GetFieldDefn(i)
    outLayer.CreateField(fieldDefn)

outLayerDefn = outLayer.GetLayerDefn()

# 遍历要素
inFeature = inLayer.GetNextFeature()
while inFeature:
    # 获取几何
    geom = inFeature.GetGeometryRef()
    # 重投影几何
    geom.Transform(coordTrans)
    # 创建要素
    outFeature = ogr.Feature(outLayerDefn)
    # 设置几何、属性
    outFeature.SetGeometry(geom)
    for i in range(0, outLayerDefn.GetFieldCount()):
        outFeature.SetField(outLayerDefn.GetFieldDefn(i).GetNameRef(), inFeature.GetField(i))
    # 添加要素
    outLayer.CreateFeature(outFeature)
    # 取消引用
    outFeature = None
    inFeature = inLayer.GetNextFeature()

# 保存并关闭
inDataSet = None
outDataSet = None

输出投影

from osgeo import ogr, osr
driver = ogr.GetDriverByName('ESRI Shapefile')
dataset = driver.Open(r'./data/test_4326.shp')
layer = dataset.GetLayer()
spatialRef = layer.GetSpatialRef()

spatialRef.ExportToWkt()
spatialRef.ExportToPrettyWkt()
spatialRef.ExportToPCI()
spatialRef.ExportToUSGS()
spatialRef.ExportToXML()

创建ESRI投影文件

from osgeo import ogr, osr

spatialRef = osr.SpatialReference()
spatialRef.ImportFromEPSG(26912)

spatialRef.MorphToESRI()
file = open('yourshpfile.prj', 'w')
file.write(spatialRef.ExportToWkt())
file.close()
回到页面顶部