Geo::GDAL  2.3
Creating a vector dataset

The code here does not have any warranty. It is recommended that before using any of this code, you look into it and try to understand what it does, what input it needs, etc. Do not blindly execute anything!

This example creates a new layer to a data source in memory. The layer will contain polygon features and each feature will contain a string as an attribute value. The name of the attribute will be 'key'. Each polygon will have four vertices. The SRS is set to WGS84.

# information that we need:
my $driver = 'Memory';
my $dsname = "."; # name of the datasource
my $lname = "boxes"; # name of the layer
my @data; # array which contains the data as hashref items,
# each item comprises items 'points' and 'key'
# 'points' is in this case an array of four points
# which are refs to arrays (x,y)
# 'key' is a string
@data = (
{ key => 'rect1', points => [[0,0],[1,0],[1,1],[0,1]] },
{ key => 'rect2', points => [[5,5],[7,5],[7,6],[5,6]] }
);
eval {
$datasource = Geo::OGR::Driver($driver)->Create($dsname);
};
die "Can't create data source $dsname: $@" if $@;
$osr = Geo::OSR::SpatialReference->new(WGS => 84);
$layer = $datasource->CreateLayer(
Name => $lname,
SRS => $osr,
# add the fields as in @data
Fields => [
{ Name => 'key', Type => 'String' },
{ Name => 'geom', Type => 'Polygon' }
]
);
for $item (@data) {
my @ring = ( $item->{points}[0],
$item->{points}[1],
$item->{points}[2],
$item->{points}[3],
$item->{points}[0] # close the ring
);
my %feature_data = (
key => $item->{key},
# a polygon is an array of rings, here we define just the outer ring
geom => { Points => [ \@ring ] }
);
$layer->InsertFeature(\%feature_data);
}
# check that we got it ok
$layer = $datasource->GetLayer($lname);
while ($feature = $layer->GetNextFeature()) {
$feature->DumpReadable;
}