[GIS] How to set the spatial reference to a OGR layer using the Python API

coordinate systemogrpython

I want to create new a Ogr Layer using the Datasource.GetLayer() method:

driver = ogr.Open(input_file).GetDriver()
datasource = driver.Open(input_file, 0)
input_layer = datasource.GetLayer()

If the input datasource does not have a spatial reference (as usually i.e. by GeoJson data) the new layer has SRS = 4326.
If I write the data to a new Postgis table, the table has 4326 as geometry srid:

output_data_source.CopyLayer(input_layer,
                                 table_name,
                                 ['OVERWRITE=YES', 'GEOMETRY_NAME=geom', 'DIM=2', 'FID=id', 'PG_USE_COPY=YES'])

How can I set the layer SRS? Something like:

input_layer.SetSrs(new_srs)

but the API does not offer a such method: (http://gdal.org/python/osgeo.ogr.Layer-class.html).
The command line tool ogr2ogr offers for this purpose the parameters s_srs and t_srs. I.e:

ogr2ogr -t_srs 'EPSG:32632' -f "PostgreSQL" PG:"dbname=test host=localhost" input.geojson

Best Answer

Not really a answer but a valid workaround: because the CreateLayer() method accept a SRS as parameter, one can create a new empty layer with the correct SRS and then fill it with the features from the input layer:

import ogr
driver = ogr.Open(input_file).GetDriver()
datasource = driver.Open(input_file, 0)
input_layer = datasource.GetLayer()

dest_srs = ogr.osr.SpatialReference()
dest_srs.ImportFromEPSG(32632)
dest_layer = output_data_source.CreateLayer(table_name,
                            dest_srs,
                            input_layer.GetLayerDefn().GetGeomType(),
                            ['OVERWRITE=YES', 'GEOMETRY_NAME=geom', 'DIM=2', 'FID=id')

# adding fields to new layer
layer_definition = ogr.Feature(input_layer.GetLayerDefn())
for i in range(layer_definition.GetFieldCount()):
    dest_layer.CreateField(layer_definition.GetFieldDefnRef(i))

# adding the features from input to dest
for i in range(0, input_layer.GetFeatureCount()):
    feature = input_layer.GetFeature(i)
    dest_layer.CreateFeature(feature)