[Gdal-dev] Transforming an ogr layer

Ari Jolma ari.jolma at tkk.fi
Wed Sep 7 14:00:44 EDT 2005


Frank Warmerdam kirjoitti:

>The perl bindings are looking good!
>  
>

they could also look much more Perlish.. Perl hackers are lazy typists..

>You need to explicitly create all the desired fields on the
>new layer.  In python this looks something like:
>  
>

Thanks, the final tutorial code is below.

Ari

# note: this code requires the CVS version of Sept. 7. 2005
use osr;
use ogr;

# the layer I'm going to tranform does not have a spatial reference 
attached to it
# so we need to create one for the sr in which it is now and one for the 
target sr

$osr_from = new osr::SpatialReference;
$osr_from->SetWellKnownGeogCS('WGS84');
$osr_to = new osr::SpatialReference;
$osr_to->ImportFromEPSG(3035);
$ct = new osr::CoordinateTransformation($osr_from,$osr_to);

# we are working in the directory /home/gis/data
# the "1" means that we plan to update the datasource
$datasource = ogr::Open('/home/gis/data/',1);

if ($datasource) {

   # open the existing layer
   $layer = $datasource->GetLayerByName('lakes');

   $feature = $layer->GetFeature(0) or die "the layer is empty";
   $geom = $feature->GetGeometryRef();
   $geom_type = $geom->GetGeometryType();

   # a new, transformed layer, similar but with the new spatial reference
   $new_layer = $datasource->CreateLayer('lakes_t', $osr_to, $geom_type);

   # copy the data model (data itself is copied automatically)
   $layer_defn = $layer->GetLayerDefn();
   for $i (0..$layer_defn->GetFieldCount()-1) {
      $new_layer->CreateField($layer_defn->GetFieldDefn($i));
   }

   # transform all features
   for $i (0..$layer->GetFeatureCount()-1) {

       $feature = $layer->GetFeature($i);
       # $geom may contain geometries etc. but there is only one root 
geometry in a feature
       $geom = $feature->GetGeometryRef();
       # the actual transformation
       $geom->Transform($ct);
       # insert into the new layer
       $new_layer->CreateFeature($feature);

   }
   
   # make sure the new layer is saved to disk
   $new_layer->SyncToDisk;
}


-- 
Prof. Ari Jolma
Kartografia ja Geoinformatiikka / Cartography and Geoinformatics
Teknillinen Korkeakoulu / Helsinki University of Technology
POBox 1200, 02015 TKK, Finland
Email: ari.jolma at tkk.fi URL: http://www.tkk.fi/~jolma




More information about the Gdal-dev mailing list