[Gdal-dev] Define/overwrite projection on shapefile

Frank Warmerdam warmerdam at pobox.com
Sat Sep 23 10:18:53 EDT 2006


Vikalpa Jetly wrote:
> How would I use ogr to set/overwrite a projection for an existing 
> shapefile? I have a wkt projection say ‘dref’ that I want to use to set 
> the projection. I understand that while creating a new shapefile I can use:
> 
>  
> 
> sref = osr.SpatialReference()
> 
> sref.ImportFromWkt(dref)
> 
> layer = datasource.CreateLayer(‘newshape’, geom_type=ogr.wkbPolygon, srs 
> = dref)
> 
>  
> 
> How would I do this for an existing shapefile? or do I need to create a 
> copy of the shapefile?

Vikalpa,

Other than creating a complete copy of the shapefile, altering the
SRS while creating the new layer, there is no way through the OGR API
to reset the SRS of a shapefile.   There is no easy way to copy a layer.
You basically need to create a new layer, add fields one at a time,
and then create features on it one at a time.

However, the shapefile projection is just kept in a .prj file.  So you
could directly alter it, instead of going through the OGR API. One thing
to keep in mind is that shapefile's .prj files are slightly altered from
the original OGR WKT.  So you need to do sref.morphToESRI() before converting
back to wkt and writing to the file.

Something like:

   sref.osr.SpatialReference()
   sref.ImportFromWkt( dref )
   sref.MorphToESRI()
   esri_wkt = sref.ExportToWKT()
   open( 'newshape.prj', 'w' ).write( esri_wkt + '\n' )

Best regards,
-- 
---------------------------------------+--------------------------------------
I set the clouds in motion - turn up   | Frank Warmerdam, warmerdam at pobox.com
light and sound - activate the windows | http://pobox.com/~warmerdam
and watch the world go round - Rush    | President OSGeo, http://osgeo.org




More information about the Gdal-dev mailing list