2 # @brief GDAL utility functions and a root class for raster classes.
3 # @details Geo::GDAL wraps many GDAL utility functions and is as a root class
4 # for all GDAL raster classes. A "raster" is an object, whose core is
5 # a rectagular grid of cells, called a "band" in GDAL. Each cell
6 # contains a numeric value of a specific data type.
10 #** @method ApplyVerticalShiftGrid()
12 sub ApplyVerticalShiftGrid {
15 #** @method BuildVRT()
18 for (keys %Geo::GDAL::Const::) {
20 push(@DATA_TYPES, $1), next
if /^GDT_(\w+)/;
21 push(@OPEN_FLAGS, $1), next
if /^OF_(\w+)/;
22 push(@RESAMPLING_TYPES, $1), next
if /^GRA_(\w+)/;
23 push(@RIO_RESAMPLING_TYPES, $1), next
if /^GRIORA_(\w+)/;
24 push(@NODE_TYPES, $1), next
if /^CXT_(\w+)/;
26 for my $string (@DATA_TYPES) {
27 my $int = eval
"\$Geo::GDAL::Const::GDT_$string";
28 $S2I{data_type}{$string} = $int;
29 $I2S{data_type}{$int} = $string;
31 for my $string (@OPEN_FLAGS) {
32 my $int = eval
"\$Geo::GDAL::Const::OF_$string";
33 $S2I{open_flag}{$string} = $int;
35 for my $string (@RESAMPLING_TYPES) {
36 my $int = eval
"\$Geo::GDAL::Const::GRA_$string";
37 $S2I{resampling}{$string} = $int;
38 $I2S{resampling}{$int} = $string;
40 for my $string (@RIO_RESAMPLING_TYPES) {
41 my $int = eval
"\$Geo::GDAL::Const::GRIORA_$string";
42 $S2I{rio_resampling}{$string} = $int;
43 $I2S{rio_resampling}{$int} = $string;
45 for my $string (@NODE_TYPES) {
46 my $int = eval
"\$Geo::GDAL::Const::CXT_$string";
47 $S2I{node_type}{$string} = $int;
48 $I2S{node_type}{$int} = $string;
52 $HAVE_PDL = 1 unless $@;
55 #** @method CPLBinaryToHex()
60 #** @method CPLHexToBinary()
65 #** @method ContourGenerateEx()
67 sub ContourGenerateEx {
70 #** @method CreatePansharpenedVRT()
72 sub CreatePansharpenedVRT {
75 #** @method scalar DataTypeIsComplex($DataType)
77 # @param DataType A GDAL raster cell data type (one of those listed by Geo::GDAL::DataTypes).
78 # @return true if the data type is a complex number.
80 sub DataTypeIsComplex {
81 return _DataTypeIsComplex(s2i(data_type => shift));
84 #** @method list DataTypeValueRange($DataType)
86 # @param DataType Data type (one of those listed by Geo::GDAL::DataTypes).
87 # @note Some returned values are inaccurate.
89 # @return the minimum, maximum range of the data type.
91 sub DataTypeValueRange {
94 # these values are from gdalrasterband.cpp
95 return (0,255)
if $t =~ /Byte/;
96 return (0,65535)
if $t =~/UInt16/;
97 return (-32768,32767)
if $t =~/Int16/;
98 return (0,4294967295)
if $t =~/UInt32/;
99 return (-2147483648,2147483647)
if $t =~/Int32/;
100 return (-4294967295.0,4294967295.0)
if $t =~/Float32/;
101 return (-4294967295.0,4294967295.0)
if $t =~/Float64/;
104 #** @method list DataTypes()
105 # Package subroutine.
106 # @return a list of GDAL raster cell data types. These are currently:
107 # Byte, CFloat32, CFloat64, CInt16, CInt32, Float32, Float64, Int16, Int32, UInt16, UInt32, and Unknown.
113 #** @method scalar DecToDMS($angle, $axis, $precision=2)
114 # Package subroutine.
115 # Convert decimal degrees to degrees, minutes, and seconds string
116 # @param angle A number
117 # @param axis A string specifying latitude or longitude ('Long').
119 # @return a string nndnn'nn.nn'"L where n is a number and L is either
125 #** @method scalar DecToPackedDMS($dec)
126 # Package subroutine.
127 # @param dec Decimal degrees
128 # @return packed DMS, i.e., a number DDDMMMSSS.SS
133 #** @method DontUseExceptions()
134 # Package subroutine.
135 # Do not use the Perl exception mechanism for GDAL messages. Instead
136 # the messages are printed to standard error.
138 sub DontUseExceptions {
141 #** @method Geo::GDAL::Driver Driver($Name)
142 # Package subroutine.
143 # Access a format driver.
144 # @param Name The short name of the driver. One of
145 # Geo::GDAL::DriverNames or Geo::OGR::DriverNames.
146 # @note This subroutine is imported into the main namespace if Geo::GDAL
147 # is used with qw/:all/.
148 # @return a Geo::GDAL::Driver object.
151 return 'Geo::GDAL::Driver' unless @_;
153 my $driver = GetDriver($name);
154 error(
"Driver \"$name\" not found. Is it built in? Check with Geo::GDAL::Drivers or Geo::OGR::Drivers.")
159 #** @method list DriverNames()
160 # Package subroutine.
161 # Available raster format drivers.
163 # perl -MGeo::GDAL -e '@d=Geo::GDAL::DriverNames;print "@d\n"'
165 # @note Use Geo::OGR::DriverNames for vector drivers.
166 # @return a list of the short names of all available GDAL raster drivers.
171 #** @method list Drivers()
172 # Package subroutine.
173 # @note Use Geo::OGR::Drivers for vector drivers.
174 # @return a list of all available GDAL raster drivers.
178 for my $i (0..GetDriverCount()-1) {
179 my $driver = GetDriver($i);
180 push @drivers, $driver
if $driver->TestCapability(
'RASTER');
185 #** @method EscapeString()
190 #** @method scalar FindFile($basename)
191 # Package subroutine.
192 # Search for GDAL support files.
197 # $a = Geo::GDAL::FindFile('pcs.csv');
198 # print STDERR "$a\n";
200 # Prints (for example):
202 # c:\msys\1.0\local\share\gdal\pcs.csv
205 # @param basename The name of the file to search for. For example
207 # @return the path to the searched file or undef.
217 #** @method FinderClean()
218 # Package subroutine.
219 # Clear the set of support file search paths.
224 #** @method GOA2GetAccessToken()
226 sub GOA2GetAccessToken {
229 #** @method GOA2GetAuthorizationURL()
231 sub GOA2GetAuthorizationURL {
234 #** @method GOA2GetRefreshToken()
236 sub GOA2GetRefreshToken {
239 #** @method GetActualURL()
244 #** @method scalar GetCacheMax()
245 # Package subroutine.
246 # @return maximum amount of memory (as bytes) for caching within GDAL.
251 #** @method scalar GetCacheUsed()
252 # Package subroutine.
253 # @return the amount of memory currently used for caching within GDAL.
258 #** @method scalar GetConfigOption($key)
259 # Package subroutine.
260 # @param key A GDAL config option. Consult <a
261 # href="https://trac.osgeo.org/gdal/wiki/ConfigOptions">the GDAL
262 # documentation</a> for available options and their use.
263 # @return the value of the GDAL config option.
265 sub GetConfigOption {
268 #** @method scalar GetDataTypeSize($DataType)
269 # Package subroutine.
270 # @param DataType A GDAL raster cell data type (one of those listed by Geo::GDAL::DataTypes).
271 # @return the size as the number of bits.
273 sub GetDataTypeSize {
274 return _GetDataTypeSize(s2i(data_type => shift, 1));
277 #** @method GetErrorCounter()
279 sub GetErrorCounter {
282 #** @method GetFileSystemOptions()
284 sub GetFileSystemOptions {
287 #** @method GetFileSystemsPrefixes()
289 sub GetFileSystemsPrefixes {
292 #** @method GetJPEG2000StructureAsString()
294 sub GetJPEG2000StructureAsString {
297 #** @method GetSignedURL()
302 #** @method Geo::GDAL::Driver IdentifyDriver($path, $siblings)
303 # Package subroutine.
304 # @param path a dataset path.
305 # @param siblings [optional] A list of names of files that belong to the data format.
306 # @return a Geo::GDAL::Driver.
311 #** @method IdentifyDriverEx()
313 sub IdentifyDriverEx {
316 #** @method MkdirRecursive()
321 #** @method Geo::GDAL::Dataset Open(%params)
322 # Package subroutine.
324 # An example, which opens an existing raster dataset for editing:
326 # use Geo::GDAL qw/:all/;
327 # $ds = Open(Name => 'existing.tiff', Access => 'Update');
329 # @param params Named parameters:
330 # - \a Name Dataset string (typically a filename). Default is '.'.
331 # - \a Access Access type, either 'ReadOnly' or 'Update'. Default is 'ReadOnly'.
332 # - \a Type Dataset type, either 'Raster', 'Vector', or 'Any'. Default is 'Any'.
333 # - \a Options A hash of GDAL open options passed to candidate drivers. Default is {}.
334 # - \a Files A list of names of files that are auxiliary to the main file. Default is [].
336 # @note This subroutine is imported into the main namespace if Geo::GDAL
337 # is use'd with qw/:all/.
339 # @note Some datasets / dataset strings do not explicitly imply the
340 # dataset type (for example a PostGIS database). If the type is not
341 # specified in such a case the returned dataset may be of either type.
343 # @return a new Geo::GDAL::Dataset object if success.
346 my $p = named_parameters(\@_, Name =>
'.', Access =>
'ReadOnly', Type =>
'Any', Options => {}, Files => []);
348 my %o = (READONLY => 1, UPDATE => 1);
349 error(1, $p->{access}, \%o) unless $o{uc($p->{access})};
350 push @flags, uc($p->{access});
351 %o = (RASTER => 1, VECTOR => 1, ANY => 1);
352 error(1, $p->{type}, \%o) unless $o{uc($p->{type})};
353 push @flags, uc($p->{type}) unless uc($p->{type}) eq
'ANY';
354 my $dataset = OpenEx(Name => $p->{name}, Flags => \@flags, Options => $p->{options}, Files => $p->{files});
356 my $t =
"Failed to open $p->{name}.";
357 $t .=
" Is it a ".lc($p->{type}).
" dataset?" unless uc($p->{type}) eq
'ANY';
363 #** @method Geo::GDAL::Dataset OpenEx(%params)
364 # Package subroutine.
365 # The generic dataset open method, used internally by all Open and OpenShared methods.
366 # @param params Named parameters:
367 # - \a Name The name of the data set or source to open. (Default is '.')
368 # - \a Flags A list of access mode flags. Available flags are listed by Geo::GDAL::OpenFlags(). (Default is [])
369 # - \a Drivers A list of short names of drivers that may be used. Empty list means all. (Default is [])
370 # - \a Options A hash of GDAL open options passed to candidate drivers. (Default is {})
371 # - \a Files A list of names of files that are auxiliary to the main file. (Default is [])
375 # $ds = Geo::GDAL::OpenEx(Name => 'existing.tiff', Flags => [qw/RASTER UPDATE/]);
377 # @return a new Geo::GDAL::Dataset object.
380 my $p = named_parameters(\@_, Name =>
'.', Flags => [], Drivers => [], Options => {}, Files => []);
384 $p = {name => $name, flags => \@flags, drivers => [], options => {}, files => []};
388 for my $flag (@{$p->{flags}}) {
389 $f |= s2i(open_flag => $flag);
393 return _OpenEx($p->{name}, $p->{flags}, $p->{drivers}, $p->{options}, $p->{files});
396 #** @method list OpenFlags()
397 # Package subroutine.
398 # @return a list of GDAL data set open modes. These are currently:
399 # ALL, GNM, RASTER, READONLY, SHARED, UPDATE, VECTOR, and VERBOSE_ERROR.
405 #** @method scalar PackCharacter($DataType)
406 # Package subroutine.
407 # Get the character that is needed for Perl's pack and unpack when
408 # they are used with Geo::GDAL::Band::ReadRaster and
409 # Geo::GDAL::Band::WriteRaster. Note that Geo::GDAL::Band::ReadTile
410 # and Geo::GDAL::Band::WriteTile have simpler interfaces that do not
411 # require pack and unpack.
412 # @param DataType A GDAL raster cell data type, typically from $band->DataType.
413 # @return a character which can be used in Perl's pack and unpack.
417 $t = i2s(data_type => $t);
418 s2i(data_type => $t); # test
419 my $is_big_endian = unpack(
"h*", pack(
"s", 1)) =~ /01/; # from Programming Perl
420 return 'C' if $t =~ /^Byte$/;
421 return ($is_big_endian ?
'n':
'v')
if $t =~ /^UInt16$/;
422 return 's' if $t =~ /^Int16$/;
423 return ($is_big_endian ?
'N' :
'V')
if $t =~ /^UInt32$/;
424 return 'l' if $t =~ /^Int32$/;
425 return 'f' if $t =~ /^Float32$/;
426 return 'd' if $t =~ /^Float64$/;
429 #** @method scalar PackedDMSToDec($packed)
430 # Package subroutine.
431 # @param packed DMS as a number DDDMMMSSS.SS
432 # @return decimal degrees
437 #** @method PopFinderLocation()
438 # Package subroutine.
439 # Remove the latest addition from the set of support file search
440 # paths. Note that calling this subroutine may remove paths GDAL put
443 sub PopFinderLocation {
446 #** @method PushFinderLocation($path)
447 # Package subroutine.
448 # Add a path to the set of paths from where GDAL support files are
449 # sought. Note that GDAL puts initially into the finder the current
450 # directory and value of GDAL_DATA environment variable (if it
451 # exists), installation directory (prepended with '/share/gdal' or
452 # '/Resources/gdal'), or '/usr/local/share/gdal'. It is usually only
453 # needed to add paths to the finder if using an alternate set of data
454 # files or a non-installed GDAL is used (as in testing).
456 sub PushFinderLocation {
459 #** @method list RIOResamplingTypes()
460 # Package subroutine.
461 # @return a list of GDAL raster IO resampling methods. These are currently:
462 # Average, Bilinear, Cubic, CubicSpline, Gauss, Lanczos, Mode, and NearestNeighbour.
464 sub RIOResamplingTypes {
465 return @RIO_RESAMPLING_TYPES;
468 #** @method list ResamplingTypes()
469 # Package subroutine.
470 # @return a list of GDAL resampling methods. These are currently:
471 # Average, Bilinear, Cubic, CubicSpline, Lanczos, Max, Med, Min, Mode, NearestNeighbour, Q1, and Q3.
473 sub ResamplingTypes {
474 return @RESAMPLING_TYPES;
477 #** @method RmdirRecursive()
482 #** @method SetCacheMax($Bytes)
483 # Package subroutine.
484 # @param Bytes New maximum amount of memory for caching within GDAL.
489 #** @method SetConfigOption($key, $value)
490 # Package subroutine.
491 # @param key A GDAL config option. Consult <a
492 # href="https://trac.osgeo.org/gdal/wiki/ConfigOptions">the GDAL
493 # documentation</a> for available options and their use.
494 # @param value A value for the option, typically 'YES', 'NO',
495 # undef, path, numeric value, or a filename.
497 sub SetConfigOption {
500 #** @method UseExceptions()
501 # Package subroutine.
502 # Use the Perl exception mechanism for GDAL messages (failures are
503 # confessed and warnings are warned) and collect the messages
504 # into \@Geo::GDAL::error. This is the default.
509 #** @method VSICurlClearCache()
511 sub VSICurlClearCache {
514 #** @method VSICurlPartialClearCache()
516 sub VSICurlPartialClearCache {
519 #** @method VSIErrorReset()
524 #** @method VSIFEofL()
529 #** @method VSIFFlushL()
534 #** @method VSIFOpenExL()
539 #** @method VSIGetLastErrorMsg()
541 sub VSIGetLastErrorMsg {
544 #** @method VSIGetLastErrorNo()
546 sub VSIGetLastErrorNo {
549 #** @method scalar VersionInfo($request = 'VERSION_NUM')
550 # Package subroutine.
551 # @param request A string specifying the request. Currently either
552 # "VERSION_NUM", "RELEASE_DATE", "RELEASE_NAME", or
553 # "--version". Default is "VERSION_NUM".
554 # @return Requested information.
559 #** @method scalar errstr()
560 # Package subroutine.
561 # Clear the error stack and return all generated GDAL error messages in one (possibly multiline) string.
562 # @return the chomped error stack joined with newlines.
568 return join(
"\n", @stack);
570 # usage: named_parameters(\@_, key value list of default parameters);
571 # returns parameters in a hash with low-case-without-_ keys
574 #** @class Geo::GDAL::AsyncReader
575 # @brief Enable asynchronous requests.
576 # @details This class is not yet documented nor tested in the GDAL Perl wrappers
577 # @todo Test and document.
579 package Geo::GDAL::AsyncReader;
583 #** @method GetNextUpdatedRegion()
585 sub GetNextUpdatedRegion {
588 #** @method LockBuffer()
593 #** @method UnlockBuffer()
598 #** @class Geo::GDAL::Band
599 # @brief A raster band.
602 package Geo::GDAL::Band;
608 # scalar (access as $band->{XSize})
613 # scalar (access as $band->{YSize})
616 #** @method AdviseRead()
621 #** @method Geo::GDAL::RasterAttributeTable AttributeTable($AttributeTable)
623 # @param AttributeTable [optional] A Geo::GDAL::RasterAttributeTable object.
624 # @return a new Geo::GDAL::RasterAttributeTable object, whose data is
625 # contained within the band.
629 SetDefaultRAT($self, $_[0])
if @_ and defined $_[0];
630 return unless defined wantarray;
631 my $r = GetDefaultRAT($self);
632 keep($r, $self)
if $r;
635 #** @method list BlockSize()
638 # @return The size of a preferred i/o raster block size as a list
644 #** @method list CategoryNames(@names)
646 # @param names [optional]
651 SetRasterCategoryNames($self, \@_)
if @_;
652 return unless defined wantarray;
653 my $n = GetRasterCategoryNames($self);
657 #** @method scalar Checksum($xoff = 0, $yoff = 0, $xsize = undef, $ysize = undef)
659 # Computes a checksum from the raster or a part of it.
664 # @return the checksum.
669 #** @method hashref ClassCounts($classifier, $progress = undef, $progress_data = undef)
671 # Compute the counts of cell values or number of cell values in ranges.
672 # @note Classifier is required only for float bands.
673 # @note NoData values are counted similar to other values when
674 # classifier is not defined for integer rasters.
676 # @param classifier Anonymous array of format [ $comparison,
677 # $classifier ], where $comparison is a string '<', '<=', '>', or '>='
678 # and $classifier is an anonymous array of format [ $value,
679 # $value|$classifier, $value|$classifier ], where $value is a numeric
680 # value against which the reclassified value is compared to. If the
681 # comparison returns true, then the second $value or $classifier is
682 # applied, and if not then the third $value or $classifier.
684 # In the example below, the line is divided into ranges
685 # [-inf..3), [3..5), and [5..inf], i.e., three ranges with class
686 # indexes 0, 1, and 2. Note that the indexes are used as keys for
687 # class counts and not the class values (here 1.0, 2.0, and 3.0),
688 # which are used in Geo::GDAL::Band::Reclassify.
690 # $classifier = [ '<', [5.0, [3.0, 1.0, 2.0], 3.0] ];
691 # # Howto create this $classifier from @class_boundaries:
692 # my $classifier = ['<='];
693 # my $tree = [$class_boundaries[0], 0, 1];
694 # for my $i (1 .. $#class_boundaries) {
695 # $tree = [$class_boundaries[$i], [@$tree], $i+1];
697 # push @$classifier, $tree;
699 # @return a reference to an anonymous hash, which contains the class
700 # values (indexes) as keys and the number of cells with that value or
701 # in that range as values. If the subroutine is user terminated an
707 #** @method scalar ColorInterpretation($color_interpretation)
709 # @note a.k.a. GetRasterColorInterpretation and GetColorInterpretation
710 # (get only and returns an integer), SetRasterColorInterpretation and
711 # SetColorInterpretation (set only and requires an integer)
712 # @param color_interpretation [optional] new color interpretation, one
713 # of Geo::GDAL::Band::ColorInterpretations.
714 # @return The color interpretation of this band. One of Geo::GDAL::Band::ColorInterpretations.
716 sub ColorInterpretation {
719 $ci = s2i(color_interpretation => $ci);
720 SetRasterColorInterpretation($self, $ci);
722 return unless defined wantarray;
723 i2s(color_interpretation => GetRasterColorInterpretation($self));
726 #** @method ColorInterpretations()
727 # Package subroutine.
728 # @return a list of types of color interpretation for raster
729 # bands. These are currently:
730 # AlphaBand, BlackBand, BlueBand, CyanBand, GrayIndex, GreenBand, HueBand, LightnessBand, MagentaBand, PaletteIndex, RedBand, SaturationBand, Undefined, YCbCr_CbBand, YCbCr_CrBand, YCbCr_YBand, and YellowBand.
732 sub ColorInterpretations {
733 return @COLOR_INTERPRETATIONS;
736 #** @method Geo::GDAL::ColorTable ColorTable($ColorTable)
738 # Get or set the color table of this band.
739 # @param ColorTable [optional] a Geo::GDAL::ColorTable object
740 # @return A new Geo::GDAL::ColorTable object which represents the
741 # internal color table associated with this band. Returns undef this
742 # band does not have an associated color table.
746 SetRasterColorTable($self, $_[0])
if @_ and defined $_[0];
747 return unless defined wantarray;
748 GetRasterColorTable($self);
751 #** @method ComputeBandStats($samplestep = 1)
753 # @param samplestep the row increment in computing the statistics.
754 # @note Returns uncorrected sample standard deviation.
756 # See also Geo::GDAL::Band::ComputeStatistics.
757 # @return a list (mean, stddev).
759 sub ComputeBandStats {
762 #** @method ComputeRasterMinMax($approx_ok = 0)
764 # @return arrayref MinMax = [min, max]
766 sub ComputeRasterMinMax {
769 #** @method list ComputeStatistics($approx_ok, $progress = undef, $progress_data = undef)
771 # @param approx_ok Whether it is allowed to compute the statistics
772 # based on overviews or similar.
773 # @note Returns uncorrected sample standard deviation.
775 # See also Geo::GDAL::Band::ComputeBandStats.
776 # @return a list ($min, $max, $mean, $stddev).
778 sub ComputeStatistics {
781 #** @method Geo::OGR::Layer Contours($DataSource, hashref LayerConstructor, $ContourInterval, $ContourBase, arrayref FixedLevels, $NoDataValue, $IDField, $ElevField, coderef Progress, $ProgressData)
783 # Generate contours for this raster band. This method can also be used with named parameters.
784 # @note This method is a wrapper for ContourGenerate.
789 # $dem = Geo::GDAL::Open('dem.gtiff');
790 # $contours = $dem->Band->Contours(ContourInterval => 10, ElevField => 'z');
791 # $n = $contours->GetFeatureCount;
794 # @param DataSource a Geo::OGR::DataSource object, default is a Memory data source
795 # @param LayerConstructor data for Geo::OGR::DataSource::CreateLayer, default is {Name => 'contours'}
796 # @param ContourInterval default is 100
797 # @param ContourBase default is 0
798 # @param FixedLevels a reference to a list of fixed contour levels, default is []
799 # @param NoDataValue default is undef
800 # @param IDField default is '', i.e., no field (the field is created if this is given)
801 # @param ElevField default is '', i.e., no field (the field is created if this is given)
802 # @param progress [optional] a reference to a subroutine, which will
803 # be called with parameters (number progress, string msg, progress_data)
804 # @param progress_data [optional]
809 my $p = named_parameters(\@_,
811 LayerConstructor => {Name =>
'contours'},
812 ContourInterval => 100,
815 NoDataValue => undef,
819 ProgressData => undef);
821 $p->{layerconstructor}->{Schema}
822 $p->{layerconstructor}->{Schema}{Fields}
824 unless ($p->{idfield} =~ /^[+-]?\d+$/ or $fields{$p->{idfield}}) {
825 push @{$p->{layerconstructor}->{Schema}{Fields}}, {Name => $p->{idfield}, Type =>
'Integer'};
827 unless ($p->{elevfield} =~ /^[+-]?\d+$/ or $fields{$p->{elevfield}}) {
828 my $type = $self->DataType() =~ /Float/ ?
'Real' :
'Integer';
829 push @{$p->{layerconstructor}->{Schema}{Fields}}, {Name => $p->{elevfield}, Type => $type};
831 my $layer = $p->{datasource}->CreateLayer($p->{layerconstructor});
832 my $schema = $layer->GetLayerDefn;
833 for (
'idfield',
'elevfield') {
834 $p->{$_} = $schema->GetFieldIndex($p->{$_}) unless $p->{$_} =~ /^[+-]?\d+$/;
836 $p->{progressdata} = 1
if $p->{progress} and not defined $p->{progressdata};
837 ContourGenerate($self, $p->{contourinterval}, $p->{contourbase}, $p->{fixedlevels},
838 $p->{nodatavalue}, $layer, $p->{idfield}, $p->{elevfield},
839 $p->{progress}, $p->{progressdata});
843 #** @method CreateMaskBand(@flags)
845 # @note May invalidate any previous mask band obtained with Geo::GDAL::Band::GetMaskBand.
847 # @param flags one or more mask flags. The flags are Geo::GDAL::Band::MaskFlags.
852 if (@_ and $_[0] =~ /^\d$/) {
856 carp
"Unknown mask flag: '$flag'." unless $MASK_FLAGS{$flag};
857 $f |= $MASK_FLAGS{$flag};
860 $self->_CreateMaskBand($f);
863 #** @method scalar DataType()
865 # @return The data type of this band. One of Geo::GDAL::DataTypes.
869 return i2s(data_type => $self->{DataType});
872 #** @method Geo::GDAL::Dataset Dataset()
874 # @return The dataset which this band belongs to.
881 #** @method scalar DeleteNoDataValue()
884 sub DeleteNoDataValue {
887 #** @method Geo::GDAL::Band Distance(%params)
889 # Compute distances to specific cells of this raster.
890 # @param params Named parameters:
891 # - \a Distance A raster band, into which the distances are computed. If not given, a not given, a new in-memory raster band is created and returned. The data type of the raster can be given in the options.
892 # - \a Options Hash of options. Options are:
893 # - \a Values A list of cell values in this band to measure the distance from. If this option is not provided, the distance will be computed to non-zero pixel values. Currently pixel values are internally processed as integers.
894 # - \a DistUnits=PIXEL|GEO Indicates whether distances will be computed in cells or in georeferenced units. The default is pixel units. This also determines the interpretation of MaxDist.
895 # - \a MaxDist=n The maximum distance to search. Distances greater than this value will not be computed. Instead output cells will be set to a NoData value.
896 # - \a NoData=n The NoData value to use on the distance band for cells that are beyond MaxDist. If not provided, the distance band will be queried for a NoData value. If one is not found, 65535 will be used (255 if the type is Byte).
897 # - \a Use_Input_NoData=YES|NO If this option is set, the NoData value of this band will be respected. Leaving NoData cells in the input as NoData pixels in the distance raster.
898 # - \a Fixed_Buf_Val=n If this option is set, all cells within the MaxDist threshold are set to this value instead of the distance value.
899 # - \a DataType The data type for the result if it is not given.
900 # - \a Progress Progress function.
901 # - \a ProgressData Additional parameter for the progress function.
903 # @note This GDAL function behind this API is called GDALComputeProximity.
905 # @return The distance raster.
909 my $p = named_parameters(\@_, Distance => undef, Options => undef, Progress => undef, ProgressData => undef);
910 for my $key (keys %{$p->{options}}) {
911 $p->{options}{uc($key)} = $p->{options}{$key};
914 unless ($p->{distance}) {
915 my ($w, $h) = $self->Size;
916 $p->{distance} =
Geo::GDAL::Driver(
'MEM')->
Create(Name =>
'distance', Width => $w, Height => $h, Type => $p->{options}{TYPE})->Band;
918 Geo::GDAL::ComputeProximity($self, $p->{distance}, $p->{options}, $p->{progress}, $p->{progressdata});
919 return $p->{distance};
922 #** @method Domains()
928 #** @method Fill($real_part, $imag_part = 0.0)
930 # Fill the band with a constant value.
931 # @param real_part Real component of fill value.
932 # @param imag_part Imaginary component of fill value.
938 #** @method FillNoData($mask, $max_search_dist, $smoothing_iterations, $options, coderef progress, $progress_data)
940 # Interpolate values for cells in this raster. The cells to fill
941 # should be marked in the mask band with zero.
943 # @param mask [optional] a mask band indicating cells to be interpolated (zero valued) (default is to get it with Geo::GDAL::Band::GetMaskBand).
944 # @param max_search_dist [optional] the maximum number of cells to
945 # search in all directions to find values to interpolate from (default is 10).
946 # @param smoothing_iterations [optional] the number of 3x3 smoothing filter passes to run (0 or more) (default is 0).
947 # @param options [optional] A reference to a hash. No options have been defined so far for this algorithm (default is {}).
948 # @param progress [optional] a reference to a subroutine, which will
949 # be called with parameters (number progress, string msg, progress_data) (default is undef).
950 # @param progress_data [optional] (default is undef).
952 # <a href="http://www.gdal.org/gdal__alg_8h.html">Documentation for GDAL algorithms</a>
957 #** @method FlushCache()
959 # Write cached data to disk. There is usually no need to call this
965 #** @method scalar GetBandNumber()
967 # @return The index of this band in the parent dataset list of bands.
972 #** @method GetBlockSize()
977 #** @method list GetDefaultHistogram($force = 1, coderef progress = undef, $progress_data = undef)
979 # @param force true to force the computation
980 # @param progress [optional] a reference to a subroutine, which will
981 # be called with parameters (number progress, string msg, progress_data)
982 # @param progress_data [optional]
983 # @note See Note in Geo::GDAL::Band::GetHistogram.
984 # @return a list: ($min, $max, arrayref histogram).
986 sub GetDefaultHistogram {
989 #** @method list GetHistogram(%parameters)
991 # Compute histogram from the raster.
992 # @param parameters Named parameters:
993 # - \a Min the lower bound, default is -0.5
994 # - \a Max the upper bound, default is 255.5
995 # - \a Buckets the number of buckets in the histogram, default is 256
996 # - \a IncludeOutOfRange whether to use the first and last values in the returned list
997 # for out of range values, default is false;
998 # the bucket size is (Max-Min) / Buckets if this is false and
999 # (Max-Min) / (Buckets-2) if this is true
1000 # - \a ApproxOK if histogram can be computed from overviews, default is false
1001 # - \a Progress an optional progress function, the default is undef
1002 # - \a ProgressData data for the progress function, the default is undef
1003 # @note Histogram counts are treated as strings in the bindings to be
1004 # able to use large integers (if GUIntBig is larger than Perl IV). In
1005 # practice this is only important if you have a 32 bit machine and
1006 # very large bucket counts. In those cases it may also be necessary to
1008 # @return a list which contains the count of values in each bucket
1012 my $p = named_parameters(\@_,
1016 IncludeOutOfRange => 0,
1019 ProgressData => undef);
1020 $p->{progressdata} = 1
if $p->{progress} and not defined $p->{progressdata};
1021 _GetHistogram($self, $p->{min}, $p->{max}, $p->{buckets},
1022 $p->{includeoutofrange}, $p->{approxok},
1023 $p->{progress}, $p->{progressdata});
1026 #** @method Geo::GDAL::Band GetMaskBand()
1028 # @return the mask band associated with this
1033 my $band = _GetMaskBand($self);
1037 #** @method list GetMaskFlags()
1039 # @return the mask flags of the mask band associated with this
1040 # band. The flags are one or more of Geo::GDAL::Band::MaskFlags.
1044 my $f = $self->_GetMaskFlags;
1046 for my $flag (keys %MASK_FLAGS) {
1047 push @f, $flag
if $f & $MASK_FLAGS{$flag};
1049 return wantarray ? @f : $f;
1052 #** @method scalar GetMaximum()
1054 # @note Call Geo::GDAL::Band::ComputeStatistics before calling
1055 # GetMaximum to make sure the value is computed.
1057 # @return statistical minimum of the band or undef if statistics are
1058 # not kept or computed in scalar context. In list context returns the
1059 # maximum value or a (kind of) maximum value supported by the data
1060 # type and a boolean value, which indicates which is the case (true is
1061 # first, false is second).
1066 #** @method scalar GetMinimum()
1068 # @note Call Geo::GDAL::Band::ComputeStatistics before calling
1069 # GetMinimum to make sure the value is computed.
1071 # @return statistical minimum of the band or undef if statistics are
1072 # not kept or computed in scalar context. In list context returns the
1073 # minimum value or a (kind of) minimum value supported by the data
1074 # type and a boolean value, which indicates which is the case (true is
1075 # first, false is second).
1080 #** @method Geo::GDAL::Band GetOverview($index)
1082 # @param index 0..GetOverviewCount-1
1083 # @return a Geo::GDAL::Band object, which represents the internal
1084 # overview band, or undef. if the index is out of bounds.
1087 my ($self, $index) = @_;
1088 my $band = _GetOverview($self, $index);
1092 #** @method scalar GetOverviewCount()
1094 # @return the number of overviews available of the band.
1096 sub GetOverviewCount {
1099 #** @method list GetStatistics($approx_ok, $force)
1101 # @param approx_ok Whether it is allowed to compute the statistics
1102 # based on overviews or similar.
1103 # @param force Whether to force scanning of the whole raster.
1104 # @note Uses Geo::GDAL::Band::ComputeStatistics internally.
1106 # @return a list ($min, $max, $mean, $stddev).
1111 #** @method HasArbitraryOverviews()
1113 # @return true or false.
1115 sub HasArbitraryOverviews {
1118 #** @method list MaskFlags()
1119 # Package subroutine.
1120 # @return the list of mask flags. These are
1121 # - \a AllValid: There are no invalid cell, all mask values will be 255.
1122 # When used this will normally be the only flag set.
1123 # - \a PerDataset: The mask band is shared between all bands on the dataset.
1124 # - \a Alpha: The mask band is actually an alpha band and may have values
1125 # other than 0 and 255.
1126 # - \a NoData: Indicates the mask is actually being generated from NoData values.
1127 # (mutually exclusive of Alpha).
1130 my @f = sort {$MASK_FLAGS{$a} <=> $MASK_FLAGS{$b}} keys %MASK_FLAGS;
1134 #** @method scalar NoDataValue($NoDataValue)
1136 # Get or set the "no data" value.
1137 # @param NoDataValue [optional]
1138 # @note $band->NoDataValue(undef) sets the NoData value to the
1139 # Posix floating point maximum. Use Geo::GDAL::Band::DeleteNoDataValue
1140 # to stop this band using a NoData value.
1141 # @return The NoData value or undef in scalar context. An undef
1142 # value indicates that there is no NoData value associated with this
1148 if (defined $_[0]) {
1149 SetNoDataValue($self, $_[0]);
1151 SetNoDataValue($self, POSIX::FLT_MAX); # hopefully an
"out of range" value
1154 GetNoDataValue($self);
1157 #** @method scalar PackCharacter()
1159 # @return The character to use in Perl pack and unpack for the data of this band.
1166 #** @method Piddle($piddle, $xoff = 0, $yoff = 0, $xsize = <width>, $ysize = <height>, $xdim, $ydim)
1168 # Read or write band data from/into a piddle.
1170 # \note The PDL module must be available for this method to work. Also, you
1171 # should 'use PDL' in the code that you use this method.
1173 # @param piddle [only when writing] The piddle from which to read the data to be written into the band.
1174 # @param xoff, yoff The offset for data in the band, default is top left (0, 0).
1175 # @param xsize, ysize [optional] The size of the window in the band.
1176 # @param xdim, ydim [optional, only when reading from a band] The size of the piddle to create.
1177 # @return A new piddle when reading from a band (no not use when writing into a band).
1180 # TODO: add Piddle sub to dataset too to make Width x Height x Bands piddles
1181 error(
"PDL is not available.") unless $Geo::GDAL::HAVE_PDL;
1183 my $t = $self->{DataType};
1184 unless (defined wantarray) {
1186 error(
"The datatype of the Piddle and the band do not match.")
1187 unless $PDL2DATATYPE{$pdl->get_datatype} == $t;
1188 my ($xoff, $yoff, $xsize, $ysize) = @_;
1191 my $data = $pdl->get_dataref();
1192 my ($xdim, $ydim) = $pdl->dims();
1193 if ($xdim > $self->{XSize} - $xoff) {
1194 warn
"Piddle XSize too large ($xdim) for this raster band (width = $self->{XSize}, offset = $xoff).";
1195 $xdim = $self->{XSize} - $xoff;
1197 if ($ydim > $self->{YSize} - $yoff) {
1198 $ydim = $self->{YSize} - $yoff;
1199 warn
"Piddle YSize too large ($ydim) for this raster band (height = $self->{YSize}, offset = $yoff).";
1203 $self->_WriteRaster($xoff, $yoff, $xsize, $ysize, $data, $xdim, $ydim, $t, 0, 0);
1206 my ($xoff, $yoff, $xsize, $ysize, $xdim, $ydim, $alg) = @_;
1214 $alg = s2i(rio_resampling => $alg);
1215 my $buf = $self->_ReadRaster($xoff, $yoff, $xsize, $ysize, $xdim, $ydim, $t, 0, 0, $alg);
1217 my $datatype = $DATATYPE2PDL{$t};
1218 error(
"The band datatype is not supported by PDL.") if $datatype < 0;
1219 $pdl->set_datatype($datatype);
1220 $pdl->setdims([$xdim, $ydim]);
1221 my $data = $pdl->get_dataref();
1224 # FIXME: we want approximate equality since no data value can be very large floating point value
1225 my $bad = GetNoDataValue($self);
1226 return $pdl->setbadif($pdl == $bad)
if defined $bad;
1230 #** @method Geo::OGR::Layer Polygonize(%params)
1232 # Polygonize this raster band.
1234 # @param params Named parameters:
1235 # - \a Mask A raster band, which is used as a mask to select polygonized areas. Default is undef.
1236 # - \a OutLayer A vector layer into which the polygons are written. If not given, an in-memory layer 'polygonized' is created and returned.
1237 # - \a PixValField The name of the field in the output layer into which the cell value of the polygon area is stored. Default is 'val'.
1238 # - \a Options Hash or list of options. Connectedness can be set to 8
1239 # to use 8-connectedness, otherwise 4-connectedness is
1240 # used. ForceIntPixel can be set to 1 to force using a 32 bit int buffer
1241 # for cell values in the process. If this is not set and the data type
1242 # of this raster does not fit into a 32 bit int buffer, a 32 bit float
1244 # - \a Progress Progress function.
1245 # - \a ProgressData Additional parameter for the progress function.
1247 # @return Output vector layer.
1251 my $p = named_parameters(\@_, Mask => undef, OutLayer => undef, PixValField =>
'val', Options => undef, Progress => undef, ProgressData => undef);
1252 my %known_options = (Connectedness => 1, ForceIntPixel => 1, DATASET_FOR_GEOREF => 1,
'8CONNECTED' => 1);
1253 for my $option (keys %{$p->{options}}) {
1254 error(1, $option, \%known_options) unless exists $known_options{$option};
1256 my $dt = $self->DataType;
1257 my %leInt32 = (Byte => 1, Int16 => 1, Int32 => 1, UInt16 => 1);
1258 my $leInt32 = $leInt32{$dt};
1259 $dt = $dt =~ /Float/ ?
'Real' :
'Integer';
1261 CreateLayer(Name =>
'polygonized',
1262 Fields => [{Name =>
'val', Type => $dt},
1263 {Name =>
'geom', Type =>
'Polygon'}]);
1264 $p->{pixvalfield} = $p->{outlayer}->GetLayerDefn->GetFieldIndex($p->{pixvalfield});
1265 $p->{options}{
'8CONNECTED'} = 1
if $p->{options}{Connectedness} && $p->{options}{Connectedness} == 8;
1266 if ($leInt32 || $p->{options}{ForceIntPixel}) {
1267 Geo::GDAL::_Polygonize($self, $p->{mask}, $p->{outlayer}, $p->{pixvalfield}, $p->{options}, $p->{progress}, $p->{progressdata});
1269 Geo::GDAL::FPolygonize($self, $p->{mask}, $p->{outlayer}, $p->{pixvalfield}, $p->{options}, $p->{progress}, $p->{progressdata});
1271 set the srs of the outlayer
if it was created here
1272 return $p->{outlayer};
1275 #** @method RasterAttributeTable()
1277 sub RasterAttributeTable {
1280 #** @method scalar ReadRaster(%params)
1282 # Read data from the band.
1284 # @param params Named parameters:
1285 # - \a XOff x offset (cell coordinates) (default is 0)
1286 # - \a YOff y offset (cell coordinates) (default is 0)
1287 # - \a XSize width of the area to read (default is the width of the band)
1288 # - \a YSize height of the area to read (default is the height of the band)
1289 # - \a BufXSize (default is undef, i.e., the same as XSize)
1290 # - \a BufYSize (default is undef, i.e., the same as YSize)
1291 # - \a BufType data type of the buffer (default is the data type of the band)
1292 # - \a BufPixelSpace (default is 0)
1293 # - \a BufLineSpace (default is 0)
1294 # - \a ResampleAlg one of Geo::GDAL::RIOResamplingTypes (default is 'NearestNeighbour'),
1295 # - \a Progress reference to a progress function (default is undef)
1296 # - \a ProgressData (default is undef)
1298 # <a href="http://www.gdal.org/classGDALDataset.html">Entry in GDAL docs (method RasterIO)</a>
1299 # @return a buffer, open the buffer with \a unpack function of Perl. See Geo::GDAL::Band::PackCharacter.
1303 my ($width, $height) = $self->Size;
1304 my ($type) = $self->DataType;
1305 my $p = named_parameters(\@_,
1315 ResampleAlg =>
'NearestNeighbour',
1317 ProgressData => undef
1319 $p->{resamplealg} = s2i(rio_resampling => $p->{resamplealg});
1320 $p->{buftype} = s2i(data_type => $p->{buftype}, 1);
1321 $self->_ReadRaster($p->{xoff},$p->{yoff},$p->{xsize},$p->{ysize},$p->{bufxsize},$p->{bufysize},$p->{buftype},$p->{bufpixelspace},$p->{buflinespace},$p->{resamplealg},$p->{progress},$p->{progressdata});
1324 #** @method array reference ReadTile($xoff = 0, $yoff = 0, $xsize = <width>, $ysize = <height>)
1326 # Read band data into a Perl array.
1328 # \note Accessing band data in this way is slow. Consider using PDL and Geo::GDAL::Band::Piddle.
1330 # Usage example (print the data from a band):
1332 # print "@$_\n" for ( @{ $band->ReadTile() } );
1334 # Another usage example (process the data of a large dataset that has one band):
1336 # my($W,$H) = $dataset->Band()->Size();
1337 # my($xoff,$yoff,$w,$h) = (0,0,200,200);
1339 # if ($xoff >= $W) {
1342 # last if $yoff >= $H;
1344 # my $data = $dataset->Band(1)->ReadTile($xoff,$yoff,min($W-$xoff,$w),min($H-$yoff,$h));
1345 # # add your data processing code here
1346 # $dataset->Band(1)->WriteTile($data,$xoff,$yoff);
1351 # return $_[0] < $_[1] ? $_[0] : $_[1];
1354 # @param xoff Number of cell to skip before starting to read from a row. Pixels are read from left to right.
1355 # @param yoff Number of cells to skip before starting to read from a column. Pixels are read from top to bottom.
1356 # @param xsize Number of cells to read from each row.
1357 # @param ysize Number of cells to read from each column.
1358 # @return a two-dimensional Perl array, organizes as data->[y][x], y =
1359 # 0..height-1, x = 0..width-1. I.e., y is row and x is column.
1362 my($self, $xoff, $yoff, $xsize, $ysize, $w_tile, $h_tile, $alg) = @_;
1370 $alg = s2i(rio_resampling => $alg);
1371 my $t = $self->{DataType};
1372 my $buf = $self->_ReadRaster($xoff, $yoff, $xsize, $ysize, $w_tile, $h_tile, $t, 0, 0, $alg);
1377 for my $y (0..$h_tile-1) {
1378 my @d = unpack($pc.
"[$w_tile]", substr($buf, $offset, $w));
1385 #** @method Reclassify($classifier, $progress = undef, $progress_data = undef)
1387 # Reclassify the cells in the band.
1388 # @note NoData values in integer rasters are reclassified if
1389 # explicitly specified in the hash classifier. However, they are not
1390 # reclassified to the default value, if one is specified. In real
1391 # valued rasters nodata cells are not reclassified.
1392 # @note If the subroutine is user terminated or the classifier is
1393 # incorrect, already reclassified cells will stay reclassified but an
1395 # @param classifier For integer rasters an anonymous hash, which
1396 # contains old class values as keys and new class values as values, or
1397 # an array classifier as in Geo::GDAL::Band::ClassCounts. In a hash
1398 # classifier a special key '*' (star) can be used as default, to act
1399 # as a fallback new class value. For real valued rasters the
1400 # classifier is as in Geo::GDAL::Band::ClassCounts.
1405 #** @method RegenerateOverview(Geo::GDAL::Band overview, $resampling, coderef progress, $progress_data)
1407 # @param overview a Geo::GDAL::Band object for the overview.
1408 # @param resampling [optional] the resampling method (one of Geo::GDAL::RIOResamplingTypes) (default is Average).
1409 # @param progress [optional] a reference to a subroutine, which will
1410 # be called with parameters (number progress, string msg, progress_data)
1411 # @param progress_data [optional]
1413 sub RegenerateOverview {
1415 #Geo::GDAL::Band overview, scalar resampling, subref callback, scalar callback_data
1417 Geo::GDAL::RegenerateOverview($self, @p);
1420 #** @method RegenerateOverviews(arrayref overviews, $resampling, coderef progress, $progress_data)
1422 # @todo This is not yet available
1424 # @param overviews a list of Geo::GDAL::Band objects for the overviews.
1425 # @param resampling [optional] the resampling method (one of Geo::GDAL::RIOResamplingTypes) (default is Average).
1426 # @param progress [optional] a reference to a subroutine, which will
1427 # be called with parameters (number progress, string msg, progress_data)
1428 # @param progress_data [optional]
1430 sub RegenerateOverviews {
1432 #arrayref overviews, scalar resampling, subref callback, scalar callback_data
1434 Geo::GDAL::RegenerateOverviews($self, @p);
1437 #** @method ScaleAndOffset($scale, $offset)
1439 # Scale and offset are used to transform raw cell values into the
1440 # units returned by GetUnits(). The conversion function is:
1442 # Units value = (raw value * scale) + offset
1444 # @return a list ($scale, $offset), the values are undefined if they
1446 # @since version 1.9 of the bindings.
1448 sub ScaleAndOffset {
1450 SetScale($self, $_[0])
if @_ > 0 and defined $_[0];
1451 SetOffset($self, $_[1])
if @_ > 1 and defined $_[1];
1452 return unless defined wantarray;
1453 my $scale = GetScale($self);
1454 my $offset = GetOffset($self);
1455 return ($scale, $offset);
1458 #** @method list SetDefaultHistogram($min, $max, $histogram)
1462 # @note See Note in Geo::GDAL::Band::GetHistogram.
1463 # @param histogram reference to an array containing the histogram
1465 sub SetDefaultHistogram {
1468 #** @method SetStatistics($min, $max, $mean, $stddev)
1470 # Save the statistics of the band if possible (the format can save
1471 # arbitrary metadata).
1480 #** @method Geo::GDAL::Band Sieve(%params)
1482 # Remove small areas by merging them into the largest neighbour area.
1483 # @param params Named parameters:
1484 # - \a Mask A raster band, which is used as a mask to select sieved areas. Default is undef.
1485 # - \a Dest A raster band into which the result is written. If not given, an new in-memory raster band is created and returned.
1486 # - \a Threshold The smallest area size (in number of cells) which are not sieved away.
1487 # - \a Options Hash or list of options. {Connectedness => 4} can be specified to use 4-connectedness, otherwise 8-connectedness is used.
1488 # - \a Progress Progress function.
1489 # - \a ProgressData Additional parameter for the progress function.
1491 # @return The filtered raster band.
1495 my $p = named_parameters(\@_, Mask => undef, Dest => undef, Threshold => 10, Options => undef, Progress => undef, ProgressData => undef);
1496 unless ($p->{dest}) {
1497 my ($w, $h) = $self->Size;
1501 if ($p->{options}{Connectedness}) {
1502 $c = $p->{options}{Connectedness};
1503 delete $p->{options}{Connectedness};
1505 Geo::GDAL::SieveFilter($self, $p->{mask}, $p->{dest}, $p->{threshold}, $c, $p->{options}, $p->{progress}, $p->{progressdata});
1509 #** @method list Size()
1511 # @return The size of the band as a list (width, height).
1515 return ($self->{XSize}, $self->{YSize});
1518 #** @method Unit($type)
1520 # @param type [optional] the unit (a string).
1521 # @note $band->Unit(undef) sets the unit value to an empty string.
1522 # @return the unit (a string).
1523 # @since version 1.9 of the bindings.
1530 SetUnitType($self, $unit);
1532 return unless defined wantarray;
1536 #** @method WriteRaster(%params)
1538 # Write data into the band.
1540 # @param params Named parameters:
1541 # - \a XOff x offset (cell coordinates) (default is 0)
1542 # - \a YOff y offset (cell coordinates) (default is 0)
1543 # - \a XSize width of the area to write (default is the width of the band)
1544 # - \a YSize height of the area to write (default is the height of the band)
1545 # - \a Buf a buffer (or a reference to a buffer) containing the data. Create the buffer with \a pack function of Perl. See Geo::GDAL::Band::PackCharacter.
1546 # - \a BufXSize (default is undef, i.e., the same as XSize)
1547 # - \a BufYSize (default is undef, i.e., the same as YSize)
1548 # - \a BufType data type of the buffer (default is the data type of the band)
1549 # - \a BufPixelSpace (default is 0)
1550 # - \a BufLineSpace (default is 0)
1552 # <a href="http://www.gdal.org/classGDALDataset.html">Entry in GDAL docs (method RasterIO)</a>
1556 my ($width, $height) = $self->Size;
1557 my ($type) = $self->DataType;
1558 my $p = named_parameters(\@_,
1570 confess
"Usage: \$band->WriteRaster( Buf => \$data, ... )" unless defined $p->{buf};
1571 $p->{buftype} = s2i(data_type => $p->{buftype}, 1);
1572 $self->_WriteRaster($p->{xoff},$p->{yoff},$p->{xsize},$p->{ysize},$p->{buf},$p->{bufxsize},$p->{bufysize},$p->{buftype},$p->{bufpixelspace},$p->{buflinespace});
1575 #** @method WriteTile($data, $xoff = 0, $yoff = 0)
1577 # Write band data from a Perl array.
1579 # \note Accessing band data in this way is slow. Consider using PDL and Geo::GDAL::Band::Piddle.
1581 # @param data A two-dimensional Perl array, organizes as data->[y][x], y =
1582 # 0..height-1, x = 0..width-1.
1588 my($self, $data, $xoff, $yoff) = @_;
1591 error(
'The data must be in a two-dimensional array') unless ref $data eq
'ARRAY' && ref $data->[0] eq
'ARRAY';
1592 my $xsize = @{$data->[0]};
1593 if ($xsize > $self->{XSize} - $xoff) {
1594 warn
"Buffer XSize too large ($xsize) for this raster band (width = $self->{XSize}, offset = $xoff).";
1595 $xsize = $self->{XSize} - $xoff;
1597 my $ysize = @{$data};
1598 if ($ysize > $self->{YSize} - $yoff) {
1599 $ysize = $self->{YSize} - $yoff;
1600 warn
"Buffer YSize too large ($ysize) for this raster band (height = $self->{YSize}, offset = $yoff).";
1603 for my $i (0..$ysize-1) {
1604 my $scanline = pack($pc.
"[$xsize]", @{$data->[$i]});
1605 $self->WriteRaster( $xoff, $yoff+$i, $xsize, 1, $scanline );
1609 #** @class Geo::GDAL::ColorTable
1610 # @brief A color table from a raster band or a color table, which can be used for a band.
1613 package Geo::GDAL::ColorTable;
1617 #** @method Geo::GDAL::ColorTable Clone()
1619 # Clone an existing color table.
1620 # @return a new Geo::GDAL::ColorTable object
1625 #** @method list Color($index, @color)
1627 # Get or set a color in this color table.
1628 # @param index The index of the color in the table. Note that the
1629 # color table may expand if the index is larger than the current max
1630 # index of this table and a color is given. An attempt to retrieve a
1631 # color out of the current size of the table causes an error.
1632 # @param color [optional] The color, either a list or a reference to a
1633 # list. If the list is too short or has undef values, the undef values
1634 # are taken as 0 except for alpha, which is taken as 255.
1635 # @note A color is an array of four integers having a value between 0
1636 # and 255: (gray, red, cyan or hue; green, magenta, or lightness;
1637 # blue, yellow, or saturation; alpha or blackband)
1638 # @return A color, in list context a list and in scalar context a reference to an anonymous array.
1643 #** @method list Colors(@colors)
1645 # Get or set the colors in this color table.
1646 # @note The color table will expand to the size of the input list but
1647 # it will not shrink.
1648 # @param colors [optional] A list of all colors (a list of lists) for this color table.
1649 # @return A list of colors (a list of lists).
1654 #** @method CreateColorRamp($start_index, arrayref start_color, $end_index, arrayref end_color)
1656 # @param start_index
1657 # @param start_color
1661 sub CreateColorRamp {
1664 #** @method scalar GetCount()
1666 # @return The number of colors in this color table.
1671 #** @method scalar GetPaletteInterpretation()
1673 # @return palette interpretation (string)
1675 sub GetPaletteInterpretation {
1677 return i2s(palette_interpretation => GetPaletteInterpretation($self));
1680 #** @method Geo::GDAL::ColorTable new($GDALPaletteInterp = 'RGB')
1682 # Create a new empty color table.
1683 # @return a new Geo::GDAL::ColorTable object
1688 $pi = s2i(palette_interpretation => $pi);
1689 my $self = Geo::GDALc::new_ColorTable($pi);
1690 bless $self, $pkg
if defined($self);
1693 #** @class Geo::GDAL::Dataset
1694 # @brief A set of associated raster bands or vector layer source.
1697 package Geo::GDAL::Dataset;
1701 #** @attr $RasterCount
1702 # scalar (access as $dataset->{RasterCount})
1705 #** @attr $RasterXSize
1706 # scalar (access as $dataset->{RasterXSize})
1709 #** @attr $RasterYSize
1710 # scalar (access as $dataset->{RasterYSize})
1713 #** @method AddBand($datatype = 'Byte', hashref options = {})
1715 # Add a new band to the dataset. The driver must support the action.
1716 # @param datatype GDAL raster cell data type (one of those listed by Geo::GDAL::DataTypes).
1717 # @param options reference to a hash of format specific options.
1718 # @return The added band.
1721 my ($self, $type, $options) = @_;
1723 $type = s2i(data_type => $type);
1724 $self->_AddBand($type, $options);
1725 return unless defined wantarray;
1726 return $self->GetRasterBand($self->{RasterCount});
1729 #** @method AdviseRead()
1734 #** @method Geo::GDAL::Band Band($index)
1736 # Create a band object for the band within the dataset.
1737 # @note a.k.a. GetRasterBand
1738 # @param index 1...RasterCount, default is 1.
1739 # @return a new Geo::GDAL::Band object
1744 #** @method list Bands()
1746 # @return a list of new Geo::GDAL::Band objects
1751 for my $i (1..$self->{RasterCount}) {
1752 push @bands, GetRasterBand($self, $i);
1757 #** @method BuildOverviews($resampling, arrayref overviews, coderef progress, $progress_data)
1759 # @param resampling the resampling method, one of Geo::GDAL::RIOResamplingTypes.
1760 # @param overviews The list of overview decimation factors to
1761 # build. For example [2,4,8].
1762 # @param progress [optional] a reference to a subroutine, which will
1763 # be called with parameters (number progress, string msg, progress_data)
1764 # @param progress_data [optional]
1766 sub BuildOverviews {
1769 $p[0] = uc($p[0])
if $p[0];
1771 $self->_BuildOverviews(@p);
1773 confess(last_error())
if $@;
1776 #** @method Geo::GDAL::Dataset BuildVRT($Dest, arrayref Sources, hashref Options, coderef progress, $progress_data)
1778 # Build a virtual dataset from a set of datasets.
1779 # @param Dest Destination raster dataset definition string (typically
1780 # filename), or an object, which implements write and close.
1781 # @param Sources A list of filenames of input datasets or a list of
1783 # @param Options See section \ref index_processing_options.
1784 # @return Dataset object
1786 # @note This subroutine is imported into the main namespace if Geo::GDAL
1787 # is use'd with qw/:all/.
1790 my ($dest, $sources, $options, $progress, $progress_data) = @_;
1791 $options = Geo::GDAL::GDALBuildVRTOptions->new(make_processing_options($options));
1792 error(
"Usage: Geo::GDAL::DataSet::BuildVRT(\$vrt_file_name, \\\@sources)")
1793 unless ref $sources eq
'ARRAY' && defined $sources->[0];
1794 unless (blessed($dest)) {
1795 if (blessed($sources->[0])) {
1796 return Geo::GDAL::wrapper_GDALBuildVRT_objects($dest, $sources, $options, $progress, $progress_data);
1798 return Geo::GDAL::wrapper_GDALBuildVRT_names($dest, $sources, $options, $progress, $progress_data);
1801 if (blessed($sources->[0])) {
1802 return stdout_redirection_wrapper(
1804 \&Geo::GDAL::wrapper_GDALBuildVRT_objects,
1805 $options, $progress, $progress_data);
1807 return stdout_redirection_wrapper(
1809 \&Geo::GDAL::wrapper_GDALBuildVRT_names,
1810 $options, $progress, $progress_data);
1815 #** @method CommitTransaction()
1817 sub CommitTransaction {
1820 #** @method Geo::GDAL::ColorTable ComputeColorTable(%params)
1822 # Compute a color table from an RGB image
1823 # @param params Named parameters:
1824 # - \a Red The red band, the default is to use the red band of this dataset.
1825 # - \a Green The green band, the default is to use the green band of this dataset.
1826 # - \a Blue The blue band, the default is to use the blue band of this dataset.
1827 # - \a NumColors The number of colors in the computed color table. Default is 256.
1828 # - \a Progress reference to a progress function (default is undef)
1829 # - \a ProgressData (default is undef)
1830 # - \a Method The computation method. The default and currently only option is the median cut algorithm.
1832 # @return a new color table object.
1834 sub ComputeColorTable {
1836 my $p = named_parameters(\@_,
1842 ProgressData => undef,
1843 Method =>
'MedianCut');
1844 for my $b ($self->Bands) {
1845 for my $cion ($b->ColorInterpretation) {
1846 if ($cion eq
'RedBand') { $p->{red}
1847 if ($cion eq
'GreenBand') { $p->{green}
1848 if ($cion eq
'BlueBand') { $p->{blue}
1852 Geo::GDAL::ComputeMedianCutPCT($p->{red},
1856 $ct, $p->{progress},
1857 $p->{progressdata});
1861 #** @method Geo::OGR::Layer CopyLayer($layer, $name, hashref options = undef)
1863 # @param layer A Geo::OGR::Layer object to be copied.
1864 # @param name A name for the new layer.
1865 # @param options A ref to a hash of format specific options.
1866 # @return a new Geo::OGR::Layer object.
1871 #** @method Geo::OGR::Layer CreateLayer(%params)
1873 # @brief Create a new vector layer into this dataset.
1875 # @param %params Named parameters:
1876 # - \a Name (scalar) name for the new layer.
1877 # - \a Fields (array reference) a list of (scalar and geometry) field definitions as in
1878 # Geo::OGR::Layer::CreateField.
1879 # - \a ApproxOK (boolean value, default is true) a flag, which is forwarded to Geo::OGR::Layer::CreateField.
1880 # - \a Options (hash reference) driver specific hash of layer creation options.
1881 # - \a Schema (hash reference, deprecated, use \a Fields and \a Name) may contain keys Name, Fields, GeomFields, GeometryType.
1882 # - \a SRS (scalar) the spatial reference for the default geometry field.
1883 # - \a GeometryType (scalar) the type of the default geometry field
1884 # (if only one geometry field). Default is 'Unknown'.
1886 # @note If Fields or Schema|Fields is not given, a default geometry
1887 # field (Name => '', GeometryType => 'Unknown') is created. If it is
1888 # given and it contains spatial fields, both GeometryType and SRS are
1889 # ignored. The type can be also set with the named parameter.
1893 # my $roads = Geo::OGR::Driver('Memory')->Create('road')->
1895 # Fields => [ { Name => 'class',
1896 # Type => 'Integer' },
1898 # Type => 'LineString25D' } ] );
1901 # @note Many formats allow only one spatial field, which currently
1902 # requires the use of GeometryType.
1904 # @return a new Geo::OGR::Layer object.
1908 my $p = named_parameters(\@_,
1911 GeometryType =>
'Unknown',
1916 error(
"The 'Fields' argument must be an array reference.")
if $p->{fields} && ref($p->{fields}) ne
'ARRAY';
1917 if (defined $p->{schema}) {
1918 my $s = $p->{schema};
1919 $p->{geometrytype} = $s->{GeometryType}
if exists $s->{GeometryType};
1920 $p->{fields} = $s->{Fields}
if exists $s->{Fields};
1921 $p->{name} = $s->{Name}
if exists $s->{Name};
1923 $p->{fields} = [] unless ref($p->{fields}) eq
'ARRAY';
1924 # if fields contains spatial fields, then do not create default one
1925 for my $f (@{$p->{fields}}) {
1926 error(
"Field definitions must be hash references.") unless ref $f eq 'HASH';
1927 if ($f->{GeometryType} || ($f->{Type} && s_exists(geometry_type => $f->{Type}))) {
1928 $p->{geometrytype} =
'None';
1932 my $gt = s2i(geometry_type => $p->{geometrytype});
1933 my $layer = _CreateLayer($self, $p->{name}, $p->{srs}, $gt, $p->{options});
1934 for my $f (@{$p->{fields}}) {
1935 $layer->CreateField($f);
1937 keep($layer, $self);
1940 #** @method CreateMaskBand()
1942 # Add a mask band to the dataset.
1944 sub CreateMaskBand {
1945 return _CreateMaskBand(@_);
1948 #** @method Geo::GDAL::Dataset DEMProcessing($Dest, $Processing, $ColorFilename, hashref Options, coderef progress, $progress_data)
1950 # Apply a DEM processing to this dataset.
1951 # @param Dest Destination raster dataset definition string (typically filename) or an object, which implements write and close.
1952 # @param Processing Processing to apply, one of "hillshade", "slope", "aspect", "color-relief", "TRI", "TPI", or "Roughness".
1953 # @param ColorFilename The color palette for color-relief.
1954 # @param Options See section \ref index_processing_options.
1955 # @param progress [optional] A reference to a subroutine, which will
1956 # be called with parameters (number progress, string msg, progress_data).
1957 # @param progress_data [optional]
1961 my ($self, $dest, $Processing, $ColorFilename, $options, $progress, $progress_data) = @_;
1962 $options = Geo::GDAL::GDALDEMProcessingOptions->new(make_processing_options($options));
1963 return $self->stdout_redirection_wrapper(
1965 \&Geo::GDAL::wrapper_GDALDEMProcessing,
1966 $Processing, $ColorFilename, $options, $progress, $progress_data
1970 #** @method Dataset()
1977 #** @method DeleteLayer($name)
1979 # Deletes a layer from the data source. Note that if there is a layer
1980 # object for the deleted layer, it becomes unusable.
1981 # @param name name of the layer to delete.
1984 my ($self, $name) = @_;
1986 for my $i (0..$self->GetLayerCount-1) {
1987 my $layer = GetLayerByIndex($self, $i);
1988 $index = $i, last
if $layer->GetName eq $name;
1990 error(2, $name,
'Layer') unless defined $index;
1991 _DeleteLayer($self, $index);
1994 #** @method Geo::GDAL::Band Dither(%params)
1996 # Compute one band with color table image from an RGB image
1997 # @params params Named parameters:
1998 # - \a Red The red band, the default is to use the red band of this dataset.
1999 # - \a Green The green band, the default is to use the green band of this dataset.
2000 # - \a Blue The blue band, the default is to use the blue band of this dataset.
2001 # - \a Dest The destination band. If this is not defined, a new in-memory band (and a dataset) will be created.
2002 # - \a ColorTable The color table for the result. If this is not defined, and the destination band does not contain one, it will be computed with the ComputeColorTable method.
2003 # - \a Progress Reference to a progress function (default is undef). Note that if ColorTable is computed using ComputeColorTable method, the progress will run twice from 0 to 1.
2004 # - \a ProgressData (default is undef)
2006 # @return the destination band.
2008 # Usage example. This code converts an RGB JPEG image into a one band PNG image with a color table.
2010 # my $d = Geo::GDAL::Open('pic.jpg');
2011 # Geo::GDAL::Driver('PNG')->Copy(Name => 'test.png', Src => $d->Dither->Dataset);
2016 my $p = named_parameters(\@_,
2023 ProgressData => undef);
2024 for my $b ($self->Bands) {
2025 for my $cion ($b->ColorInterpretation) {
2026 if ($cion eq
'RedBand') { $p->{red}
2027 if ($cion eq
'GreenBand') { $p->{green}
2028 if ($cion eq
'BlueBand') { $p->{blue}
2031 my ($w, $h) = $self->Size;
2039 Green => $p->{green},
2041 Progress => $p->{progress},
2042 ProgressData => $p->{progressdata});
2043 Geo::GDAL::DitherRGB2PCT($p->{red},
2049 $p->{progressdata});
2054 #** @method Domains()
2060 #** @method Geo::GDAL::Driver Driver()
2062 # @note a.k.a. GetDriver
2063 # @return a Geo::GDAL::Driver object that was used to open or create this dataset.
2068 #** @method Geo::OGR::Layer ExecuteSQL($statement, $geom = undef, $dialect = "")
2070 # @param statement A SQL statement.
2071 # @param geom A Geo::OGR::Geometry object.
2073 # @return a new Geo::OGR::Layer object. The data source object will
2074 # exist as long as the layer object exists.
2078 my $layer = $self->_ExecuteSQL(@_);
2079 note($layer,
"is result set");
2080 keep($layer, $self);
2083 #** @method Geo::GDAL::Extent Extent(@params)
2085 # @param params nothing, or a list ($xoff, $yoff, $w, $h)
2086 # @return A new Geo::GDAL::Extent object that represents the area that
2087 # this raster or the specified tile covers.
2091 my $t = $self->GeoTransform;
2092 my $extent = $t->Extent($self->Size);
2094 my ($xoff, $yoff, $w, $h) = @_;
2095 my ($x, $y) = $t->Apply([$xoff, $xoff+$w, $xoff+$w, $xoff], [$yoff, $yoff, $yoff+$h, $yoff+$h]);
2096 my $xmin = shift @$x;
2099 $xmin = $x
if $x < $xmin;
2100 $xmax = $x
if $x > $xmax;
2102 my $ymin = shift @$y;
2105 $ymin = $y
if $y < $ymin;
2106 $ymax = $y
if $y > $ymax;
2113 #** @method list GCPs(@GCPs, Geo::OSR::SpatialReference sr)
2115 # Get or set the GCPs and their projection.
2116 # @param GCPs [optional] a list of Geo::GDAL::GCP objects
2117 # @param sr [optional] the projection of the GCPs.
2118 # @return a list of Geo::GDAL::GCP objects followed by a Geo::OSR::SpatialReference object.
2124 $proj = $proj->Export(
'WKT')
if $proj and ref($proj);
2125 SetGCPs($self, \@_, $proj);
2127 return unless defined wantarray;
2129 my $GCPs = GetGCPs($self);
2130 return (@$GCPs, $proj);
2133 #** @method Geo::GDAL::GeoTransform GeoTransform(Geo::GDAL::GeoTransform $geo_transform)
2135 # Transformation from cell coordinates (column,row) to projection
2138 # x = geo_transform[0] + column*geo_transform[1] + row*geo_transform[2]
2139 # y = geo_transform[3] + column*geo_transform[4] + row*geo_transform[5]
2141 # @param geo_transform [optional]
2142 # @return the geo transform in a non-void context.
2148 SetGeoTransform($self, $_[0]);
2150 SetGeoTransform($self, \@_);
2153 confess(last_error())
if $@;
2154 return unless defined wantarray;
2155 my $t = GetGeoTransform($self);
2163 #** @method GetDriver()
2168 #** @method list GetFileList()
2170 # @return list of files GDAL believes to be part of this dataset.
2175 #** @method scalar GetGCPProjection()
2177 # @return projection string.
2179 sub GetGCPProjection {
2182 #** @method Geo::OGR::Layer GetLayer($name)
2184 # @param name the name of the requested layer. If not given, then
2185 # returns the first layer in the data source.
2186 # @return a new Geo::OGR::Layer object that represents the layer
2187 # in the data source.
2190 my($self, $name) = @_;
2191 my $layer = defined $name ? GetLayerByName($self,
"$name") : GetLayerByIndex($self, 0);
2193 error(2, $name,
'Layer') unless $layer;
2194 keep($layer, $self);
2197 #** @method list GetLayerNames()
2199 # @note Delivers the functionality of undocumented method GetLayerCount.
2200 # @return a list of the names of the layers this data source provides.
2205 for my $i (0..$self->GetLayerCount-1) {
2206 my $layer = GetLayerByIndex($self, $i);
2207 push @names, $layer->GetName;
2212 #** @method GetNextFeature()
2214 sub GetNextFeature {
2217 #** @method GetStyleTable()
2222 #** @method Geo::GDAL::Dataset Grid($Dest, hashref Options)
2224 # Creates a regular raster grid from this data source.
2225 # This is equivalent to the gdal_grid utility.
2226 # @param Dest Destination raster dataset definition string (typically
2227 # filename) or an object, which implements write and close.
2228 # @param Options See section \ref index_processing_options.
2231 my ($self, $dest, $options, $progress, $progress_data) = @_;
2232 $options = Geo::GDAL::GDALGridOptions->new(make_processing_options($options));
2233 return $self->stdout_redirection_wrapper(
2235 \&Geo::GDAL::wrapper_GDALGrid,
2236 $options, $progress, $progress_data
2240 #** @method scalar Info(hashref Options)
2242 # Information about this dataset.
2243 # @param Options See section \ref index_processing_options.
2246 my ($self, $o) = @_;
2247 $o = Geo::GDAL::GDALInfoOptions->new(make_processing_options($o));
2248 return GDALInfo($self, $o);
2251 #** @method Geo::GDAL::Dataset Nearblack($Dest, hashref Options, coderef progress, $progress_data)
2253 # Convert nearly black/white pixels to black/white.
2254 # @param Dest Destination raster dataset definition string (typically
2255 # filename), destination dataset to which to add an alpha or mask
2256 # band, or an object, which implements write and close.
2257 # @param Options See section \ref index_processing_options.
2258 # @return Dataset if destination dataset definition string was given,
2259 # otherwise a boolean for success/fail but the method croaks if there
2263 my ($self, $dest, $options, $progress, $progress_data) = @_;
2264 $options = Geo::GDAL::GDALNearblackOptions->new(make_processing_options($options));
2265 my $b = blessed($dest);
2266 if ($b && $b eq
'Geo::GDAL::Dataset') {
2267 Geo::GDAL::wrapper_GDALNearblackDestDS($dest, $self, $options, $progress, $progress_data);
2269 return $self->stdout_redirection_wrapper(
2271 \&Geo::GDAL::wrapper_GDALNearblackDestName,
2272 $options, $progress, $progress_data
2277 #** @method Geo::GDAL::Dataset Open()
2278 # Package subroutine.
2279 # The same as Geo::GDAL::Open
2284 #** @method Geo::GDAL::Dataset OpenShared()
2285 # Package subroutine.
2286 # The same as Geo::GDAL::OpenShared
2291 #** @method Geo::GDAL::Dataset Rasterize($Dest, hashref Options, coderef progress, $progress_data)
2293 # Render data from this data source into a raster.
2294 # @param Dest Destination raster dataset definition string (typically
2295 # filename), destination dataset, or an object, which implements write and close.
2296 # @param Options See section \ref index_processing_options.
2297 # @return Dataset if destination dataset definition string was given,
2298 # otherwise a boolean for success/fail but the method croaks if there
2303 my ($self, $dest, $options, $progress, $progress_data) = @_;
2304 $options = Geo::GDAL::GDALRasterizeOptions->new(make_processing_options($options));
2305 my $b = blessed($dest);
2306 if ($b && $b eq
'Geo::GDAL::Dataset') {
2307 Geo::GDAL::wrapper_GDALRasterizeDestDS($dest, $self, $options, $progress, $progress_data);
2309 # TODO: options need to force a new raster be made, otherwise segfault
2310 return $self->stdout_redirection_wrapper(
2312 \&Geo::GDAL::wrapper_GDALRasterizeDestName,
2313 $options, $progress, $progress_data
2318 #** @method scalar ReadRaster(%params)
2320 # Read data from the dataset.
2322 # @param params Named parameters:
2323 # - \a XOff x offset (cell coordinates) (default is 0)
2324 # - \a YOff y offset (cell coordinates) (default is 0)
2325 # - \a XSize width of the area to read (default is the width of the dataset)
2326 # - \a YSize height of the area to read (default is the height of the dataset)
2327 # - \a BufXSize (default is undef, i.e., the same as XSize)
2328 # - \a BufYSize (default is undef, i.e., the same as YSize)
2329 # - \a BufType data type of the buffer (default is the data type of the first band)
2330 # - \a BandList a reference to an array of band indices (default is [1])
2331 # - \a BufPixelSpace (default is 0)
2332 # - \a BufLineSpace (default is 0)
2333 # - \a BufBandSpace (default is 0)
2334 # - \a ResampleAlg one of Geo::GDAL::RIOResamplingTypes (default is 'NearestNeighbour'),
2335 # - \a Progress reference to a progress function (default is undef)
2336 # - \a ProgressData (default is undef)
2338 # <a href="http://www.gdal.org/classGDALDataset.html">Entry in GDAL docs (method RasterIO)</a>
2339 # @return a buffer, open the buffer with \a unpack function of Perl. See Geo::GDAL::Band::PackCharacter.
2343 my ($width, $height) = $self->Size;
2344 my ($type) = $self->Band->DataType;
2345 my $p = named_parameters(\@_,
2357 ResampleAlg =>
'NearestNeighbour',
2359 ProgressData => undef
2361 $p->{resamplealg} = s2i(rio_resampling => $p->{resamplealg});
2362 $p->{buftype} = s2i(data_type => $p->{buftype}, 1);
2363 $self->_ReadRaster($p->{xoff},$p->{yoff},$p->{xsize},$p->{ysize},$p->{bufxsize},$p->{bufysize},$p->{buftype},$p->{bandlist},$p->{bufpixelspace},$p->{buflinespace},$p->{bufbandspace},$p->{resamplealg},$p->{progress},$p->{progressdata});
2366 #** @method ReadTile()
2369 my ($self, $xoff, $yoff, $xsize, $ysize, $w_tile, $h_tile, $alg) = @_;
2371 for my $i (0..$self->Bands-1) {
2372 $data[$i] = $self->Band($i+1)->ReadTile($xoff, $yoff, $xsize, $ysize, $w_tile, $h_tile, $alg);
2377 #** @method ReleaseResultSet($layer)
2379 # @param layer A layer the has been created with ExecuteSQL.
2380 # @note There is no need to call this method. The result set layer is
2381 # released in the destructor of the layer that was created with SQL.
2383 sub ReleaseResultSet {
2384 # a no-op, _ReleaseResultSet is called from Layer::DESTROY
2387 #** @method ResetReading()
2392 #** @method RollbackTransaction()
2394 sub RollbackTransaction {
2397 #** @method SetStyleTable()
2402 #** @method list Size()
2404 # @return (width, height)
2408 return ($self->{RasterXSize}, $self->{RasterYSize});
2411 #** @method Geo::OSR::SpatialReference SpatialReference(Geo::OSR::SpatialReference sr)
2413 # Get or set the projection of this dataset.
2414 # @param sr [optional] a Geo::OSR::SpatialReference object,
2415 # which replaces the existing projection definition of this dataset.
2416 # @return a Geo::OSR::SpatialReference object, which represents the
2417 # projection of this dataset.
2418 # @note Methods GetProjection, SetProjection, and Projection return WKT strings.
2420 sub SpatialReference {
2421 my($self, $sr) = @_;
2422 SetProjection($self, $sr->As(
'WKT'))
if defined $sr;
2423 if (defined wantarray) {
2424 my $p = GetProjection($self);
2430 #** @method StartTransaction()
2432 sub StartTransaction {
2435 #** @method TestCapability()
2437 sub TestCapability {
2438 return _TestCapability(@_);
2441 #** @method Tile(Geo::GDAL::Extent e)
2443 # Compute the top left cell coordinates and width and height of the
2444 # tile that covers the given extent.
2445 # @param e The extent whose tile is needed.
2446 # @note Requires that the raster is a strictly north up one.
2447 # @return A list ($xoff, $yoff, $xsize, $ysize).
2450 my ($self, $e) = @_;
2451 my ($w, $h) = $self->Size;
2452 my $t = $self->GeoTransform;
2453 confess
"GeoTransform is not \"north up\"." unless $t->NorthUp;
2454 my $xoff = floor(($e->[0] - $t->[0])/$t->[1]);
2455 $xoff = 0
if $xoff < 0;
2456 my $yoff = floor(($e->[1] - $t->[3])/$t->[5]);
2457 $yoff = 0
if $yoff < 0;
2458 my $xsize = ceil(($e->[2] - $t->[0])/$t->[1]) - $xoff;
2459 $xsize = $w - $xoff
if $xsize > $w - $xoff;
2460 my $ysize = ceil(($e->[3] - $t->[3])/$t->[5]) - $yoff;
2461 $ysize = $h - $yoff
if $ysize > $h - $yoff;
2462 return ($xoff, $yoff, $xsize, $ysize);
2465 #** @method Geo::GDAL::Dataset Translate($Dest, hashref Options, coderef progress, $progress_data)
2467 # Convert this dataset into another format.
2468 # @param Dest Destination dataset definition string (typically
2469 # filename) or an object, which implements write and close.
2470 # @param Options See section \ref index_processing_options.
2471 # @return New dataset object if destination dataset definition
2472 # string was given, otherwise a boolean for success/fail but the
2473 # method croaks if there was an error.
2476 my ($self, $dest, $options, $progress, $progress_data) = @_;
2477 return $self->stdout_redirection_wrapper(
2481 #** @method Geo::GDAL::Dataset Warp($Dest, hashref Options, coderef progress, $progress_data)
2483 # Reproject this dataset.
2484 # @param Dest Destination raster dataset definition string (typically
2485 # filename) or an object, which implements write and close.
2486 # @param Options See section \ref index_processing_options.
2487 # @note This method can be run as a package subroutine with a list of
2488 # datasets as the first argument to mosaic several datasets.
2491 my ($self, $dest, $options, $progress, $progress_data) = @_;
2492 # can be run as object method (one dataset) and as package sub (a list of datasets)
2493 $options = Geo::GDAL::GDALWarpAppOptions->new(make_processing_options($options));
2494 my $b = blessed($dest);
2495 $self = [$self] unless ref $self eq
'ARRAY';
2496 if ($b && $b eq
'Geo::GDAL::Dataset') {
2497 Geo::GDAL::wrapper_GDALWarpDestDS($dest, $self, $options, $progress, $progress_data);
2499 return stdout_redirection_wrapper(
2502 \&Geo::GDAL::wrapper_GDALWarpDestName,
2503 $options, $progress, $progress_data
2508 #** @method Geo::GDAL::Dataset Warped(%params)
2510 # Create a virtual warped dataset from this dataset.
2512 # @param params Named parameters:
2513 # - \a SrcSRS Override the spatial reference system of this dataset if there is one (default is undef).
2514 # - \a DstSRS The target spatial reference system of the result (default is undef).
2515 # - \a ResampleAlg The resampling algorithm (default is 'NearestNeighbour').
2516 # - \a MaxError Maximum error measured in input cellsize that is allowed in approximating the transformation (default is 0 for exact calculations).
2518 # # <a href="http://www.gdal.org/gdalwarper_8h.html">Documentation for GDAL warper.</a>
2520 # @return a new Geo::GDAL::Dataset object
2524 my $p = named_parameters(\@_, SrcSRS => undef, DstSRS => undef, ResampleAlg =>
'NearestNeighbour', MaxError => 0);
2525 for my $srs (qw/srcsrs dstsrs/) {
2526 $p->{$srs} = $p->{$srs}->ExportToWkt
if $p->{$srs} && blessed $p->{$srs};
2528 $p->{resamplealg} = s2i(resampling => $p->{resamplealg});
2529 my $warped = Geo::GDAL::_AutoCreateWarpedVRT($self, $p->{srcsrs}, $p->{dstsrs}, $p->{resamplealg}, $p->{maxerror});
2530 keep($warped, $self)
if $warped; #
self must live as
long as warped
2533 #** @method WriteRaster(%params)
2535 # Write data into the dataset.
2537 # @param params Named parameters:
2538 # - \a XOff x offset (cell coordinates) (default is 0)
2539 # - \a YOff y offset (cell coordinates) (default is 0)
2540 # - \a XSize width of the area to write (default is the width of the dataset)
2541 # - \a YSize height of the area to write (default is the height of the dataset)
2542 # - \a Buf a buffer (or a reference to a buffer) containing the data. Create the buffer with \a pack function of Perl. See Geo::GDAL::Band::PackCharacter.
2543 # - \a BufXSize (default is undef, i.e., the same as XSize)
2544 # - \a BufYSize (default is undef, i.e., the same as YSize)
2545 # - \a BufType data type of the buffer (default is the data type of the first band)
2546 # - \a BandList a reference to an array of band indices (default is [1])
2547 # - \a BufPixelSpace (default is 0)
2548 # - \a BufLineSpace (default is 0)
2549 # - \a BufBandSpace (default is 0)
2551 # <a href="http://www.gdal.org/classGDALDataset.html">Entry in GDAL docs (method RasterIO)</a>
2555 my ($width, $height) = $self->Size;
2556 my ($type) = $self->Band->DataType;
2557 my $p = named_parameters(\@_,
2571 $p->{buftype} = s2i(data_type => $p->{buftype}, 1);
2572 $self->_WriteRaster($p->{xoff},$p->{yoff},$p->{xsize},$p->{ysize},$p->{buf},$p->{bufxsize},$p->{bufysize},$p->{buftype},$p->{bandlist},$p->{bufpixelspace},$p->{buflinespace},$p->{bufbandspace});
2575 #** @method WriteTile()
2578 my ($self, $data, $xoff, $yoff) = @_;
2581 for my $i (0..$self->Bands-1) {
2582 $self->Band($i+1)->WriteTile($data->[$i], $xoff, $yoff);
2586 #** @class Geo::GDAL::Driver
2587 # @brief A driver for a specific dataset format.
2590 package Geo::GDAL::Driver;
2594 #** @attr $HelpTopic
2595 # $driver->{HelpTopic}
2599 # $driver->{LongName}
2602 #** @attr $ShortName
2603 # $driver->{ShortName}
2606 #** @method list Capabilities()
2608 # @return A list of capabilities. When executed as a package subroutine
2609 # returns a list of all potential capabilities a driver may have. When
2610 # executed as an object method returns a list of all capabilities the
2613 # Currently capabilities are:
2614 # CREATE, CREATECOPY, DEFAULT_FIELDS, NOTNULL_FIELDS, NOTNULL_GEOMFIELDS, OPEN, RASTER, VECTOR, and VIRTUALIO.
2618 # @all_capabilities = Geo::GDAL::Driver::Capabilities;
2619 # @capabilities_of_the_geotiff_driver = Geo::GDAL::Driver('GTiff')->Capabilities;
2624 return @CAPABILITIES unless $self;
2625 my $h = $self->GetMetadata;
2627 for my $cap (@CAPABILITIES) {
2628 my $test = $h->{
'DCAP_'.uc($cap)};
2629 push @cap, $cap
if defined($test) and $test eq
'YES';
2634 #** @method Geo::GDAL::Dataset Copy(%params)
2636 # Create a new raster Geo::GDAL::Dataset as a copy of an existing dataset.
2637 # @note a.k.a. CreateCopy
2639 # @param params Named parameters:
2640 # - \a Name name for the new raster dataset.
2641 # - \a Src the source Geo::GDAL::Dataset object.
2642 # - \a Strict 1 (default) if the copy must be strictly equivalent, or 0 if the copy may adapt.
2643 # - \a Options an anonymous hash of driver specific options.
2644 # - \a Progress [optional] a reference to a subroutine, which will
2645 # be called with parameters (number progress, string msg, progress_data).
2646 # - \a ProgressData [optional]
2647 # @return a new Geo::GDAL::Dataset object.
2651 my $p = named_parameters(\@_, Name =>
'unnamed', Src => undef, Strict => 1, Options => {}, Progress => undef, ProgressData => undef);
2652 return $self->stdout_redirection_wrapper(
2654 $self->can(
'_CreateCopy'),
2655 $p->{src}, $p->{strict}, $p->{options}, $p->{progress}, $p->{progressdata});
2658 #** @method CopyFiles($NewName, $OldName)
2660 # Copy the files of a dataset.
2661 # @param NewName String.
2662 # @param OldName String.
2667 #** @method Geo::GDAL::Dataset Create(%params)
2669 # Create a raster dataset using this driver.
2670 # @note a.k.a. CreateDataset
2672 # @param params Named parameters:
2673 # - \a Name The name for the dataset (default is 'unnamed') or an object, which implements write and close.
2674 # - \a Width The width for the raster dataset (default is 256).
2675 # - \a Height The height for the raster dataset (default is 256).
2676 # - \a Bands The number of bands to create into the raster dataset (default is 1).
2677 # - \a Type The data type for the raster cells (default is 'Byte'). One of Geo::GDAL::Driver::CreationDataTypes.
2678 # - \a Options Driver creation options as a reference to a hash (default is {}).
2680 # @return A new Geo::GDAL::Dataset object.
2684 my $p = named_parameters(\@_, Name =>
'unnamed', Width => 256, Height => 256, Bands => 1, Type =>
'Byte', Options => {});
2685 my $type = s2i(data_type => $p->{type});
2686 return $self->stdout_redirection_wrapper(
2688 $self->can(
'_Create'),
2689 $p->{width}, $p->{height}, $p->{bands}, $type, $p->{options}
2693 #** @method list CreationDataTypes()
2695 # @return a list of data types that can be used for new datasets of this format. A subset of Geo::GDAL::DataTypes
2697 sub CreationDataTypes {
2699 my $h = $self->GetMetadata;
2700 return split /\s+/, $h->{DMD_CREATIONDATATYPES}
if $h->{DMD_CREATIONDATATYPES};
2703 #** @method list CreationOptionList()
2705 # @return a list of options, each option is a hashref, the keys are
2706 # name, type and description or Value. Value is a listref.
2708 sub CreationOptionList {
2711 my $h = $self->GetMetadata->{DMD_CREATIONOPTIONLIST};
2713 $h = ParseXMLString($h);
2714 my($type, $value) = NodeData($h);
2715 if ($value eq
'CreationOptionList') {
2716 for my $o (Children($h)) {
2718 for my $a (Children($o)) {
2719 my(undef, $key) = NodeData($a);
2720 my(undef, $value) = NodeData(Child($a, 0));
2721 if ($key eq
'Value') {
2722 push @{$option{$key}}, $value;
2724 $option{$key} = $value;
2727 push @options, \%option;
2734 #** @method Delete($name)
2741 #** @method Domains()
2747 #** @method scalar Extension()
2749 # @note The returned extension does not contain a '.' prefix.
2750 # @return a suggested single extension or a list of extensions (in
2751 # list context) for datasets.
2755 my $h = $self->GetMetadata;
2757 my $e = $h->{DMD_EXTENSIONS};
2758 my @e = split / /, $e;
2760 for my $i (0..$#e) {
2765 my $e = $h->{DMD_EXTENSION};
2766 return '' if $e =~ /\
2772 #** @method scalar MIMEType()
2774 # @return a suggested MIME type for datasets.
2778 my $h = $self->GetMetadata;
2779 return $h->{DMD_MIMETYPE};
2782 #** @method scalar Name()
2784 # @return The short name of the driver.
2788 return $self->{ShortName};
2793 # The same as Geo::GDAL::Open except that only this driver is allowed.
2797 my @p = @_; # name, update
2798 my @flags = qw/RASTER/;
2799 push @flags, qw/READONLY/
if $p[1] eq
'ReadOnly';
2800 push @flags, qw/UPDATE/
if $p[1] eq
'Update';
2801 my $dataset = OpenEx($p[0], \@flags, [$self->Name()]);
2802 error(
"Failed to open $p[0]. Is it a raster dataset?") unless $dataset;
2806 #** @method Rename($NewName, $OldName)
2808 # Rename (move) a GDAL dataset.
2809 # @param NewName String.
2810 # @param OldName String.
2815 #** @method scalar TestCapability($cap)
2817 # Test whether the driver has the specified capability.
2818 # @param cap A capability string (one of those returned by Capabilities).
2819 # @return a boolean value.
2821 sub TestCapability {
2822 my($self, $cap) = @_;
2823 my $h = $self->GetMetadata->{
'DCAP_'.uc($cap)};
2824 return (defined($h) and $h eq
'YES') ? 1 : undef;
2827 #** @method stdout_redirection_wrapper()
2829 sub stdout_redirection_wrapper {
2830 my ($self, $name, $sub, @params) = @_;
2832 if ($name && blessed $name) {
2834 my $ref = $object->can(
'write');
2835 VSIStdoutSetRedirection($ref);
2836 $name =
'/vsistdout/';
2840 $ds = $sub->($self, $name, @params);
2844 $Geo::GDAL::stdout_redirection{tied(%$ds)} = $object;
2846 VSIStdoutUnsetRedirection();
2850 confess(last_error()) if $@;
2851 confess("Failed. Use Geo::OGR::Driver for vector drivers.") unless $ds;
2855 #** @class Geo::GDAL::Extent
2856 # @brief A rectangular area in projection coordinates: xmin, ymin, xmax, ymax.
2858 package Geo::GDAL::Extent;
2860 #** @method ExpandToInclude($extent)
2861 # Package subroutine.
2862 # Extends this extent to include the other extent.
2863 # @param extent Another Geo::GDAL::Extent object.
2865 sub ExpandToInclude {
2866 my ($self, $e) = @_;
2867 return if $e->IsEmpty;
2868 if ($self->IsEmpty) {
2871 $self->[0] = $e->[0]
if $e->[0] < $self->[0];
2872 $self->[1] = $e->[1]
if $e->[1] < $self->[1];
2873 $self->[2] = $e->[2]
if $e->[2] > $self->[2];
2874 $self->[3] = $e->[3]
if $e->[3] > $self->[3];
2878 #** @method IsEmpty()
2882 return $self->[2] < $self->[0];
2885 #** @method scalar Overlap($extent)
2886 # Package subroutine.
2887 # @param extent Another Geo::GDAL::Extent object.
2888 # @return A new, possibly empty, Geo::GDAL::Extent object, which
2889 # represents the joint area of the two extents.
2892 my ($self, $e) = @_;
2895 $ret->[0] = $e->[0]
if $self->[0] < $e->[0];
2896 $ret->[1] = $e->[1]
if $self->[1] < $e->[1];
2897 $ret->[2] = $e->[2]
if $self->[2] > $e->[2];
2898 $ret->[3] = $e->[3]
if $self->[3] > $e->[3];
2902 #** @method scalar Overlaps($extent)
2903 # Package subroutine.
2904 # @param extent Another Geo::GDAL::Extent object.
2905 # @return True if this extent overlaps the other extent, false otherwise.
2908 my ($self, $e) = @_;
2909 return $self->[0] < $e->[2] && $self->[2] > $e->[0] && $self->[1] < $e->[3] && $self->[3] > $e->[1];
2912 #** @method list Size()
2913 # Package subroutine.
2914 # @return A list ($width, $height).
2918 return (0,0)
if $self->
IsEmpty;
2919 return ($self->[2] - $self->[0], $self->[3] - $self->[1]);
2922 #** @method Geo::GDAL::Extent new(@params)
2923 # Package subroutine.
2924 # @param params nothing, a list ($xmin, $ymin, $xmax, $ymax), or an Extent object
2925 # @return A new Extent object (empty if no parameters, a copy of the parameter if it is an Extent object).
2932 } elsif (ref $_[0]) {
2937 bless $self, $class;
2941 #** @class Geo::GDAL::GCP
2942 # @brief A ground control point for georeferencing rasters.
2945 package Geo::GDAL::GCP;
2950 # cell x coordinate (access as $gcp->{Column})
2954 # unique identifier (string) (access as $gcp->{Id})
2958 # informational message (access as $gcp->{Info})
2962 # cell y coordinate (access as $gcp->{Row})
2966 # projection coordinate (access as $gcp->{X})
2970 # projection coordinate (access as $gcp->{Y})
2974 # projection coordinate (access as $gcp->{Z})
2977 #** @method scalar new($x = 0.0, $y = 0.0, $z = 0.0, $column = 0.0, $row = 0.0, $info = "", $id = "")
2979 # @param x projection coordinate
2980 # @param y projection coordinate
2981 # @param z projection coordinate
2982 # @param column cell x coordinate
2983 # @param row cell y coordinate
2984 # @param info informational message
2985 # @param id unique identifier (string)
2986 # @return a new Geo::GDAL::GCP object
2990 my $self = Geo::GDALc::new_GCP(@_);
2991 bless $self, $pkg
if defined($self);
2994 #** @class Geo::GDAL::GeoTransform
2995 # @brief An array of affine transformation coefficients.
2996 # @details The geo transformation has the form
2998 # x = a + column * b + row * c
2999 # y = d + column * e + row * f
3002 # (column,row) is the location in cell coordinates, and
3003 # (x,y) is the location in projection coordinates, or vice versa.
3004 # A Geo::GDAL::GeoTransform object is a reference to an anonymous array [a,b,c,d,e,f].
3006 package Geo::GDAL::GeoTransform;
3008 #** @method Apply($x, $y)
3010 # @param x Column or x, or a reference to an array of columns or x's
3011 # @param y Row or y, or a reference to an array of rows or y's
3012 # @return a list (x, y), where x and y are the transformed coordinates
3013 # or references to arrays of transformed coordinates.
3016 my ($self, $columns, $rows) = @_;
3017 return Geo::GDAL::ApplyGeoTransform($self, $columns, $rows) unless ref($columns) eq
'ARRAY';
3019 for my $i (0..$#$columns) {
3021 Geo::GDAL::ApplyGeoTransform($self, $columns->[$i], $rows->[$i]);
3028 # @return a new Geo::GDAL::GeoTransform object, which is the inverse
3029 # of this one (in void context changes this object).
3033 my @inv = Geo::GDAL::InvGeoTransform($self);
3038 #** @method NorthUp()
3042 return $self->[2] == 0 && $self->[4] == 0;
3045 #** @method new(@params)
3047 # @param params nothing, a reference to an array [a,b,c,d,e,f], a list
3048 # (a,b,c,d,e,f), or named parameters
3049 # - \a GCPs A reference to an array of Geo::GDAL::GCP objects.
3050 # - \a ApproxOK Minimize the error in the coefficients (integer, default is 1 (true), used with GCPs).
3051 # - \a Extent A Geo::GDAL::Extent object used to obtain the coordinates of the up left corner position.
3052 # - \a CellSize The cell size (width and height) (default is 1, used with Extent).
3054 # @note When Extent is specifid, the created geo transform will be
3055 # north up, have square cells, and coefficient f will be -1 times the
3056 # cell size (image y - row - will increase downwards and projection y
3057 # will increase upwards).
3058 # @return a new Geo::GDAL::GeoTransform object.
3064 $self = [0,1,0,0,0,1];
3065 } elsif (ref $_[0]) {
3067 } elsif ($_[0] =~ /^[a-zA-Z]/i) {
3068 my $p = named_parameters(\@_, GCPs => undef, ApproxOK => 1,
Extent => undef, CellSize => 1);
3070 $self = Geo::GDAL::GCPsToGeoTransform($p->{gcps}, $p->{approxok});
3071 } elsif ($p->{extent}) {
3074 error(
"Missing GCPs or Extent");
3080 bless $self, $class;
3083 #** @class Geo::GDAL::MajorObject
3084 # @brief An object, which holds meta data.
3087 package Geo::GDAL::MajorObject;
3091 #** @method scalar Description($description)
3093 # @param description [optional]
3094 # @return the description in a non-void context.
3097 my($self, $desc) = @_;
3098 SetDescription($self, $desc)
if defined $desc;
3099 GetDescription($self)
if defined wantarray;
3102 #** @method Domains()
3103 # Package subroutine.
3104 # @return the class specific DOMAINS list
3110 #** @method scalar GetDescription()
3114 sub GetDescription {
3117 #** @method hash reference GetMetadata($domain = "")
3119 # @note see Metadata
3126 #** @method GetMetadataDomainList()
3128 sub GetMetadataDomainList {
3131 #** @method hash reference Metadata(hashref metadata = undef, $domain = '')
3135 # @return the metadata in a non-void context.
3139 my $metadata = ref $_[0] ? shift : undef;
3141 SetMetadata($self, $metadata, $domain)
if defined $metadata;
3142 GetMetadata($self, $domain)
if defined wantarray;
3145 #** @method SetDescription($NewDesc)
3150 sub SetDescription {
3153 #** @method SetMetadata(hashref metadata, $domain = "")
3155 # @note see Metadata
3163 #** @class Geo::GDAL::RasterAttributeTable
3164 # @brief An attribute table in a raster band.
3167 package Geo::GDAL::RasterAttributeTable;
3178 #** @method ChangesAreWrittenToFile()
3180 sub ChangesAreWrittenToFile {
3183 #** @method Geo::GDAL::RasterAttributeTable Clone()
3185 # @return a new Geo::GDAL::RasterAttributeTable object
3190 #** @method hash Columns(%columns)
3192 # A get/set method for the columns of the RAT
3193 # @param columns optional, a the keys are column names and the values are anonymous
3194 # hashes with keys Type and Usage
3195 # @return a hash similar to the optional input parameter
3200 if (@_) { # create columns
3202 for my $name (keys %columns) {
3203 $self->CreateColumn($name, $columns{$name}{Type}, $columns{$name}{Usage});
3207 for my $c (0..$self->GetColumnCount-1) {
3208 my $name = $self->GetNameOfCol($c);
3209 $columns{$name}{Type} = $self->GetTypeOfCol($c);
3210 $columns{$name}{Usage} = $self->GetUsageOfCol($c);
3215 #** @method CreateColumn($name, $type, $usage)
3218 # @param type one of FieldTypes
3219 # @param usage one of FieldUsages
3222 my($self, $name, $type, $usage) = @_;
3223 for my $color (qw/Red Green Blue Alpha/) {
3224 carp
"RAT column type will be 'Integer' for usage '$color'." if $usage eq $color and $type ne
'Integer';
3226 $type = s2i(rat_field_type => $type);
3227 $usage = s2i(rat_field_usage => $usage);
3228 _CreateColumn($self, $name, $type, $usage);
3231 #** @method DumpReadable()
3236 #** @method list FieldTypes()
3237 # Package subroutine.
3241 return @FIELD_TYPES;
3244 #** @method list FieldUsages()
3245 # Package subroutine.
3249 return @FIELD_USAGES;
3252 #** @method scalar GetColOfUsage($usage)
3258 my($self, $usage) = @_;
3259 _GetColOfUsage($self, s2i(rat_field_usage => $usage));
3262 #** @method scalar GetColumnCount()
3266 sub GetColumnCount {
3269 #** @method scalar GetNameOfCol($column)
3277 #** @method scalar GetRowCount()
3283 #** @method scalar GetRowOfValue($value)
3285 # @param value a cell value
3286 # @return row index or -1
3291 #** @method GetTableType()
3296 #** @method scalar GetTypeOfCol($column)
3302 my($self, $col) = @_;
3303 i2s(rat_field_type => _GetTypeOfCol($self, $col));
3306 #** @method scalar GetUsageOfCol($column)
3312 my($self, $col) = @_;
3313 i2s(rat_field_usage => _GetUsageOfCol($self, $col));
3316 #** @method scalar GetValueAsDouble($row, $column)
3322 sub GetValueAsDouble {
3325 #** @method scalar GetValueAsInt($row, $column)
3334 #** @method scalar GetValueAsString($row, $column)
3340 sub GetValueAsString {
3343 #** @method LinearBinning($Row0MinIn, $BinSizeIn)
3345 # @param Row0MinIn [optional] the lower bound (cell value) of the first category.
3346 # @param BinSizeIn [optional] the width of each category (in cell value units).
3347 # @return ($Row0MinIn, $BinSizeIn) or an empty list if LinearBinning is not set.
3351 SetLinearBinning($self, @_)
if @_ > 0;
3352 return unless defined wantarray;
3353 my @a = GetLinearBinning($self);
3354 return $a[0] ? ($a[1], $a[2]) : ();
3357 #** @method SetRowCount($count)
3365 #** @method SetTableType()
3370 #** @method SetValueAsDouble($row, $column, $value)
3377 sub SetValueAsDouble {
3380 #** @method SetValueAsInt($row, $column, $value)
3390 #** @method SetValueAsString($row, $column, $value)
3397 sub SetValueAsString {
3400 #** @method scalar Value($row, $column, $value)
3404 # @param value [optional]
3408 my($self, $row, $column) = @_;
3409 SetValueAsString($self, $row, $column, $_[3])
if defined $_[3];
3410 return unless defined wantarray;
3411 GetValueAsString($self, $row, $column);
3414 #** @method Geo::GDAL::RasterAttributeTable new()
3416 # @return a new Geo::GDAL::RasterAttributeTable object
3420 my $self = Geo::GDALc::new_RasterAttributeTable(@_);
3421 bless $self, $pkg
if defined($self);
3424 #** @class Geo::GDAL::Transformer
3426 # @details This class is not yet documented for the GDAL Perl bindings.
3427 # @todo Test and document.
3429 package Geo::GDAL::Transformer;
3433 #** @method TransformGeolocations()
3435 sub TransformGeolocations {
3438 #** @method TransformPoint()
3440 sub TransformPoint {
3447 my $self = Geo::GDALc::new_Transformer(@_);
3448 bless $self, $pkg
if defined($self);
3451 #** @class Geo::GDAL::VSIF
3452 # @brief A GDAL virtual file system.
3455 package Geo::GDAL::VSIF;
3457 use base qw(Exporter)
3464 Geo::GDAL::VSIFCloseL($self);
3474 #** @method MkDir($path)
3475 # Package subroutine.
3477 # @param path The directory to make.
3478 # @note The name of this method is VSIMkdir in GDAL.
3482 # mode unused in CPL
3483 Geo::GDAL::Mkdir($path, 0);
3486 #** @method Geo::GDAL::VSIF Open($filename, $mode)
3487 # Package subroutine.
3488 # @param filename Name of the file to open. For example "/vsimem/x".
3489 # @param mode Access mode. 'r', 'r+', 'w', etc.
3490 # @return A file handle on success.
3493 my ($path, $mode) = @_;
3494 my $self = Geo::GDAL::VSIFOpenL($path, $mode);
3495 bless $self,
'Geo::GDAL::VSIF';
3498 #** @method scalar Read($count)
3500 # @param count The number of bytes to read from the file.
3501 # @return A byte string.
3504 my ($self, $count) = @_;
3505 Geo::GDAL::VSIFReadL($count, $self);
3508 #** @method list ReadDir($dir)
3509 # Package subroutine.
3510 # @return Contents of a directory in an anonymous array or as a list.
3514 Geo::GDAL::ReadDir($path);
3517 #** @method scalar ReadDirRecursive($dir)
3518 # Package subroutine.
3519 # @note Give the directory in the form '/vsimem', i.e., without trailing '/'.
3520 # @return Contents of a directory tree in an anonymous array.
3522 sub ReadDirRecursive {
3524 Geo::GDAL::ReadDirRecursive($path);
3527 #** @method Rename($old, $new)
3528 # Package subroutine.
3530 # @note The name of this method is VSIRename in GDAL.
3533 my ($old, $new) = @_;
3534 Geo::GDAL::Rename($old, $new);
3537 #** @method RmDir($path)
3538 # Package subroutine.
3539 # Remove a directory.
3540 # @note The name of this method is VSIRmdir in GDAL.
3543 my ($dirname, $recursive) = @_;
3546 Geo::GDAL::Rmdir($dirname);
3548 for my $f (ReadDir($dirname)) {
3549 next
if $f eq
'..' or $f eq
'.';
3550 my @s = Stat($dirname.
'/'.$f);
3552 Unlink($dirname.
'/'.$f);
3553 } elsif ($s[0] eq
'd') {
3554 Rmdir($dirname.
'/'.$f, 1);
3555 Rmdir($dirname.
'/'.$f);
3562 my $r = $recursive ?
' recursively' :
'';
3563 error(
"Cannot remove directory \"$dirname\"$r.");
3567 #** @method Seek($offset, $whence)
3571 my ($self, $offset, $whence) = @_;
3572 Geo::GDAL::VSIFSeekL($self, $offset, $whence);
3575 #** @method list Stat($filename)
3576 # Package subroutine.
3577 # @return ($filemode, $filesize). filemode is f for a plain file, d
3578 # for a directory, l for a symbolic link, p for a named pipe (FIFO), S
3579 # for a socket, b for a block special file, and c for a character
3584 Geo::GDAL::Stat($path);
3587 #** @method scalar Tell()
3592 Geo::GDAL::VSIFTellL($self);
3595 #** @method Truncate($new_size)
3599 my ($self, $new_size) = @_;
3600 Geo::GDAL::VSIFTruncateL($self, $new_size);
3603 #** @method Unlink($filename)
3604 # Package subroutine.
3605 # @param filename The file to delete.
3606 # @return 0 on success and -1 on an error.
3609 my ($filename) = @_;
3610 Geo::GDAL::Unlink($filename);
3613 #** @method Write($scalar)
3615 # @param scalar The byte string to write to the file.
3616 # @return Number of bytes written into the file.
3619 my ($self, $data) = @_;
3620 Geo::GDAL::VSIFWriteL($data, $self);
3623 #** @class Geo::GDAL::VSILFILE
3625 package Geo::GDAL::VSILFILE;
3629 #** @class Geo::GDAL::XML
3630 # @brief A simple XML parser
3633 package Geo::GDAL::XML;
3635 #** @method new($string)
3637 # @param string String containing XML.
3638 # @return A new Geo::GDAL::XML object, which is a reference to an anonymous array.
3643 my $self = ParseXMLString($xml);
3644 bless $self, $class;
3645 $self->traverse(sub {my $node = shift; bless $node, $class});
3649 #** @method serialize()
3651 # @return The XML serialized into a string.
3655 return SerializeXMLTree($self);
3658 # This file was automatically generated by SWIG (http://www.swig.org).
3661 # Do not make changes to this file unless you know what you are doing--modify
3662 # the SWIG interface file instead.
3665 #** @method traverse(coderef subroutine)
3667 # @param subroutine Code reference, which will be called for each node in the XML with parameters: node, node_type, node_value. Node type is either Attribute, Comment, Element, Literal, or Text.
3670 my ($self, $sub) = @_;
3671 my $type = $self->[0];
3672 my $data = $self->[1];
3673 $type = NodeType($type);
3674 $sub->($self, $type, $data);
3675 for my $child (@{$self}[2..$#$self]) {
3676 traverse($child, $sub);
3681 # @brief Base class for geographical networks in GDAL.
3686 #** @method CastToGenericNetwork()
3688 sub CastToGenericNetwork {
3691 #** @method CastToNetwork()
3696 #** @method GATConnectedComponents()
3698 sub GATConnectedComponents {
3701 #** @method GATDijkstraShortestPath()
3703 sub GATDijkstraShortestPath {
3706 #** @method GATKShortestPath()
3708 sub GATKShortestPath {
3711 #** @method GNM_EDGE_DIR_BOTH()
3713 sub GNM_EDGE_DIR_BOTH {
3716 #** @method GNM_EDGE_DIR_SRCTOTGT()
3718 sub GNM_EDGE_DIR_SRCTOTGT {
3721 #** @method GNM_EDGE_DIR_TGTTOSRC()
3723 sub GNM_EDGE_DIR_TGTTOSRC {
3727 #** @class Geo::GNM::GenericNetwork
3730 package Geo::GNM::GenericNetwork;
3734 #** @method ChangeAllBlockState()
3736 sub ChangeAllBlockState {
3739 #** @method ChangeBlockState()
3741 sub ChangeBlockState {
3744 #** @method ConnectFeatures()
3746 sub ConnectFeatures {
3749 #** @method ConnectPointsByLines()
3751 sub ConnectPointsByLines {
3754 #** @method CreateRule()
3759 #** @method DeleteAllRules()
3761 sub DeleteAllRules {
3764 #** @method DeleteRule()
3769 #** @method DisconnectFeatures()
3771 sub DisconnectFeatures {
3774 #** @method DisconnectFeaturesWithId()
3776 sub DisconnectFeaturesWithId {
3779 #** @method GetRules()
3784 #** @method ReconnectFeatures()
3786 sub ReconnectFeatures {
3789 #** @class Geo::GNM::MajorObject
3792 package Geo::GNM::MajorObject;
3794 #** @class Geo::GNM::Network
3797 package Geo::GNM::Network;
3801 #** @method CommitTransaction()
3803 sub CommitTransaction {
3806 #** @method CopyLayer()
3811 #** @method DisconnectAll()
3816 #** @method GetFeatureByGlobalFID()
3818 sub GetFeatureByGlobalFID {
3821 #** @method GetFileList()
3826 #** @method GetLayerByIndex()
3828 sub GetLayerByIndex {
3831 #** @method GetLayerByName()
3833 sub GetLayerByName {
3836 #** @method GetLayerCount()
3841 #** @method GetName()
3846 #** @method GetPath()
3851 #** @method GetProjection()
3856 #** @method GetProjectionRef()
3858 sub GetProjectionRef {
3861 #** @method GetVersion()
3866 #** @method RollbackTransaction()
3868 sub RollbackTransaction {
3871 #** @method StartTransaction()
3873 sub StartTransaction {
3877 # @brief OGR utility functions.
3878 # @details A wrapper for many OGR utility functions and a root class for all
3883 #** @method list ByteOrders()
3884 # Package subroutine.
3885 # @return a list of byte order types, XDR and NDR. XDR denotes
3886 # big-endian and NDR denotes little-endian.
3891 #** @method Geo::GDAL::Driver Driver($name)
3892 # Package subroutine.
3894 # @param name the short name of the driver.
3895 # @note No check is made that the driver is actually a vector driver.
3896 # @return a Geo::GDAL::Driver object.
3899 return 'Geo::GDAL::Driver' unless @_;
3903 #** @method list DriverNames()
3904 # Package subroutine.
3905 # A.k.a GetDriverNames
3907 # perl -MGeo::GDAL -e '@d=Geo::OGR::DriverNames;print "@d\n"'
3909 # @note Use Geo::GDAL::DriverNames for raster drivers.
3910 # @return a list of the short names of all available GDAL vector drivers.
3915 #** @method list Drivers()
3916 # Package subroutine.
3917 # @note Use Geo::GDAL::Drivers for raster drivers.
3918 # @return a list of all available GDAL vector drivers.
3922 for my $i (0..GetDriverCount()-1) {
3923 my $driver = Geo::GDAL::GetDriver($i);
3924 push @drivers, $driver
if $driver->TestCapability(
'VECTOR');
3929 #** @method Flatten()
3934 #** @method scalar GeometryTypeModify($type, $modifier)
3936 # @param type a geometry type (one of Geo::OGR::GeometryTypes).
3937 # @param modifier one of 'flatten', 'set_Z', 'make_collection', 'make_curve', or 'make_linear'.
3938 # @return modified geometry type.
3940 sub GeometryTypeModify {
3941 my($type, $modifier) = @_;
3942 $type = s2i(geometry_type => $type);
3943 return i2s(geometry_type => GT_Flatten($type))
if $modifier =~ /flat/i;
3944 return i2s(geometry_type => GT_SetZ($type))
if $modifier =~ /z/i;
3945 return i2s(geometry_type => GT_GetCollection($type))
if $modifier =~ /collection/i;
3946 return i2s(geometry_type => GT_GetCurve($type))
if $modifier =~ /curve/i;
3947 return i2s(geometry_type => GT_GetLinear($type))
if $modifier =~ /linear/i;
3948 error(1, $modifier, {Flatten => 1, SetZ => 1, GetCollection => 1, GetCurve => 1, GetLinear => 1});
3951 #** @method scalar GeometryTypeTest($type, $test, $type2)
3953 # @param type a geometry type (one of Geo::OGR::GeometryTypes).
3954 # @param test one of 'has_z', 'is_subclass_of', 'is_curve', 'is_surface', or 'is_non_linear'.
3955 # @param type2 a geometry type (one of Geo::OGR::GeometryTypes). Required for 'is_subclass_of' test.
3956 # @return result of the test.
3958 sub GeometryTypeTest {
3959 my($type, $test, $type2) = @_;
3960 $type = s2i(geometry_type => $type);
3961 if (defined $type2) {
3962 $type = s2i(geometry_type => $type);
3964 error(
"Usage: GeometryTypeTest(type1, 'is_subclass_of', type2).") if $test =~ /subclass/i;
3966 return GT_HasZ($type) if $test =~ /z/i;
3967 return GT_IsSubClassOf($type, $type2) if $test =~ /subclass/i;
3968 return GT_IsCurve($type) if $test =~ /curve/i;
3969 return GT_IsSurface($type) if $test =~ /surface/i;
3970 return GT_IsNonLinear($type) if $test =~ /linear/i;
3971 error(1, $test, {HasZ => 1, IsSubClassOf => 1, IsCurve => 1, IsSurface => 1, IsNonLinear => 1});
3974 #** @method list GeometryTypes()
3975 # Package subroutine.
3976 # @return a list of all geometry types, currently:
3977 # CircularString, CircularStringM, CircularStringZ, CircularStringZM, CompoundCurve, CompoundCurveM, CompoundCurveZ, CompoundCurveZM, Curve, CurveM, CurvePolygon, CurvePolygonM, CurvePolygonZ, CurvePolygonZM, CurveZ, CurveZM, GeometryCollection, GeometryCollection25D, GeometryCollectionM, GeometryCollectionZM, LineString, LineString25D, LineStringM, LineStringZM, LinearRing, MultiCurve, MultiCurveM, MultiCurveZ, MultiCurveZM, MultiLineString, MultiLineString25D, MultiLineStringM, MultiLineStringZM, MultiPoint, MultiPoint25D, MultiPointM, MultiPointZM, MultiPolygon, MultiPolygon25D, MultiPolygonM, MultiPolygonZM, MultiSurface, MultiSurfaceM, MultiSurfaceZ, MultiSurfaceZM, None, Point, Point25D, PointM, PointZM, Polygon, Polygon25D, PolygonM, PolygonZM, PolyhedralSurface, PolyhedralSurfaceM, PolyhedralSurfaceZ, PolyhedralSurfaceZM, Surface, SurfaceM, SurfaceZ, SurfaceZM, TIN, TINM, TINZ, TINZM, Triangle, TriangleM, TriangleZ, TriangleZM, and Unknown.
3981 # This file was automatically generated by SWIG (http://www.swig.org).
3984 # Do not make changes to this file unless you know what you are doing--modify
3985 # the SWIG interface file instead.
3988 #** @method GetNonLinearGeometriesEnabledFlag()
3990 sub GetNonLinearGeometriesEnabledFlag {
3993 #** @method GetOpenDSCount()
3995 sub GetOpenDSCount {
4008 #** @method Geo::GDAL::Dataset Open($name, $update = 0)
4010 # Open a vector data source.
4011 # @param name The data source string (directory, filename, etc.).
4012 # @param update Whether to open the data source in update mode (default is not).
4013 # @return a new Geo::GDAL::Dataset object.
4016 my @p = @_; # name, update
4017 my @flags = qw/VECTOR/;
4018 push @flags, qw/UPDATE/
if $p[1];
4020 error(
"Failed to open $p[0]. Is it a vector dataset?") unless $dataset;
4024 #** @method Geo::GDAL::Dataset OpenShared($name, $update = 0)
4026 # Open a vector data source in shared mode.
4027 # @param name The data source string (directory, filename, etc.).
4028 # @param update Whether to open the data source in update mode.
4029 # @return a new Geo::GDAL::Dataset object.
4032 my @p = @_; # name, update
4033 my @flags = qw/VECTOR SHARED/;
4034 push @flags, qw/UPDATE/
if $p[1];
4036 error(
"Failed to open $p[0]. Is it a vector dataset?") unless $dataset;
4040 #** @method SetGenerate_DB2_V72_BYTE_ORDER($Generate_DB2_V72_BYTE_ORDER)
4042 # Needed only on IBM DB2.
4044 sub SetGenerate_DB2_V72_BYTE_ORDER {
4047 #** @method SetNonLinearGeometriesEnabledFlag()
4049 sub SetNonLinearGeometriesEnabledFlag {
4052 #** @class Geo::OGR::DataSource
4053 # @brief A vector dataset.
4054 # @details This is a legacy class which should not be
4055 # used in new code. Use Geo::GDAL::Dataset.
4057 package Geo::OGR::DataSource;
4059 #** @method Geo::GDAL::Dataset Open()
4060 # Package subroutine.
4061 # The same as Geo::OGR::Open
4066 #** @method Geo::GDAL::Dataset OpenShared()
4067 # Package subroutine.
4068 # The same as Geo::OGR::OpenShared
4073 #** @class Geo::OGR::Driver
4074 # @brief A vector format driver.
4075 # @details This is a legacy class which
4076 # should not be used in new code. Use Geo::GDAL::Driver.
4078 package Geo::OGR::Driver;
4082 #** @method Geo::GDAL::Dataset Copy(Geo::GDAL::Dataset source, $name, arrayref options = undef)
4084 # Copy a vector data source into a new data source with this driver.
4085 # @param source The Geo::GDAL::Dataset object to be copied.
4086 # @param name The name for the new data source.
4087 # @param options Driver specific options. In addition to options
4088 # specified in GDAL documentation the option STRICT can be set to 'NO'
4089 # for a more relaxed copy. Otherwise the STRICT is 'YES'.
4090 # @note The order of the first two parameters is different from that in Geo::GDAL::Driver::Copy.
4091 # @return a new Geo::GDAL::Dataset object.
4094 my ($self, @p) = @_; # src, name, options
4095 my $strict = 1; # the
default in bindings
4096 $strict = 0
if $p[2] && $p[2]->{STRICT} eq
'NO';
4097 $self->SUPER::Copy($p[1], $p[0], $strict, @{$p[2..4]}); # path, src, strict, options, cb, cb_data
4100 #** @method Geo::GDAL::Dataset Create($name, hashref options = undef )
4102 # Create a new vector data source using this driver.
4103 # @param name The data source name.
4104 # @param options Driver specific dataset creation options.
4107 my ($self, $name, $options) = @_; # name, options
4109 $self->SUPER::Create(Name => $name, Width => 0, Height => 0, Bands => 0, Type =>
'Byte', Options => $options);
4114 # The same as Geo::OGR::Open except that only this driver is allowed.
4118 my @p = @_; # name, update
4119 my @flags = qw/VECTOR/;
4120 push @flags, qw/UPDATE/
if $p[1];
4122 error(
"Failed to open $p[0]. Is it a vector dataset?") unless $dataset;
4126 #** @class Geo::OGR::Feature
4127 # @brief A collection of non-spatial and spatial attributes.
4128 # @details A feature is a collection of non-spatial and spatial attributes and
4129 # an id, which is a special attribute, and data records according to
4130 # this data model. Attributes are called fields and some fields are
4131 # spatial, i.e., their value is a geometry. Fields have at least a
4132 # name and a type. Features may exist within a layer or
4133 # separetely. The data model of a feature is a definition object.
4135 package Geo::OGR::Feature;
4139 #** @method Geo::OGR::Feature Clone()
4141 # @return a new Geo::OGR::Feature object
4146 #** @method DumpReadable()
4148 # Write the contents of this feature to stdout.
4153 #** @method scalar Equal($feature)
4155 # @param feature a Geo::OGR::Feature object for comparison
4161 #** @method scalar FID($id)
4163 # @brief Get or set the id of this feature.
4164 # @param id [optional] the id to set for this feature.
4165 # @return integer the id of this feature.
4169 $self->SetFID($_[0])
if @_;
4170 return unless defined wantarray;
4174 #** @method Field($name, $value, ...)
4176 # @brief Get, set, or unset the field value.
4177 # @param name the name (or the index) of the field.
4178 # @param value a scalar, a list of scalars or a reference to a
4179 # list. If undef, the field is unset. If a scalar or a list of
4180 # scalars, the field is set from them.
4181 # @note Non-scalar fields (for example Date) can be set either from a
4182 # scalar, which is then assumed to be a string and parsed, or from a
4183 # list of values (for example year, month, day for Date).
4184 # @note Setting and getting Integer64 fields requires 'use bigint' if
4185 # \$Config{ivsize} is smaller than 8, i.e., in a 32 bit machine.
4186 # @return in non-void context the value of the field, which may be a
4187 # scalar or a list, depending on the field type. For unset fields the
4188 # undef value is returned.
4192 my $field = $self->GetFieldIndex(shift
4193 $self->SetField($field, @_)
if @_;
4194 $self->GetField($field)
if defined wantarray;
4197 #** @method FillUnsetWithDefault()
4199 sub FillUnsetWithDefault {
4202 #** @method Geometry($name, $geometry)
4204 # @brief Get or set the value of a geometry field.
4205 # @note This method delivers the functionality of undocumented methods
4206 # SetGeometry($geometry), SetGeometryDirectly, SetGeomField,
4207 # SetGeomFieldDirectly, GetGeometry, GetGeometryRef.
4209 # Set or get the geometry in the feature. When setting, does a check
4210 # against the schema (GeometryType) of the feature. If the parameter
4211 # is a geometry object, it is cloned.
4212 # @param name [optional] the name of the spatial field,
4213 # whose geometry is to be set. If not given, sets or gets the geometry
4214 # of the first (or the single) spatial field.
4215 # @param geometry [optional] a Geo::OGR::Geometry object or a
4216 # reference to a hash from which such can be created (using
4217 # Geo::OGR::Geometry::new).
4218 # @return in a non-void context the indicated geometry in the feature
4219 # as a Geo::OGR::Geometry object. The returned object contains a
4220 # reference to the actual geometry data in the feature (the geometry
4221 # is not cloned) and to the feature object, thus keeping the feature
4222 # object from being destroyed while the geometry object exists.
4226 my $field = ((@_ > 0 and ref($_[0]) eq
'') or (@_ > 2 and @_ % 2 == 1)) ? shift : 0;
4227 $field = $self->GetGeomFieldIndex($field);
4229 if (@_ and @_ % 2 == 0) {
4235 my $type = $self->GetDefn->GetGeomFieldDefn($field)->Type;
4236 if (blessed($geometry) and $geometry->isa(
'Geo::OGR::Geometry')) {
4237 my $gtype = $geometry->GeometryType;
4238 error(
"The type of the inserted geometry ('$gtype') is not the same as the type of the field ('$type').")
4239 if $type ne
'Unknown' and $type ne $gtype;
4241 $self->SetGeomFieldDirectly($field, $geometry->Clone);
4243 confess last_error() if $@;
4244 } elsif (ref($geometry) eq 'HASH') {
4245 $geometry->{GeometryType}
4249 confess last_error() if $@;
4250 my $gtype = $geometry->GeometryType;
4251 error("The type of the inserted geometry ('$gtype') is not the same as the type of the field ('$type').")
4252 if $type ne 'Unknown' and $type ne $gtype;
4254 $self->SetGeomFieldDirectly($field, $geometry);
4256 confess last_error() if $@;
4258 error(
"Usage: \$feature->Geometry([field],[geometry])");
4261 return unless defined wantarray;
4262 $geometry = $self->GetGeomFieldRef($field);
4263 return unless $geometry;
4264 keep($geometry, $self);
4267 #** @method Geo::OGR::FeatureDefn GetDefn()
4269 # @note A.k.a GetDefnRef.
4270 # @return a Geo::OGR::FeatureDefn object, which represents the definition of this feature.
4274 my $defn = $self->GetDefnRef;
4278 #** @method scalar GetFID()
4280 # @return the feature id (an integer).
4285 #** @method list GetField($name)
4290 my ($self, $field) = @_;
4291 $field = $self->GetFieldIndex($field);
4292 return unless IsFieldSet($self, $field);
4293 my $type = GetFieldType($self, $field);
4294 return GetFieldAsInteger($self, $field)
if $type == $Geo::OGR::OFTInteger;
4295 return GetFieldAsInteger64($self, $field)
if $type == $Geo::OGR::OFTInteger64;
4296 return GetFieldAsDouble($self, $field)
if $type == $Geo::OGR::OFTReal;
4297 return GetFieldAsString($self, $field)
if $type == $Geo::OGR::OFTString;
4298 if ($type == $Geo::OGR::OFTIntegerList) {
4299 my $ret = GetFieldAsIntegerList($self, $field);
4300 return wantarray ? @$ret : $ret;
4302 if ($type == $Geo::OGR::OFTInteger64List) {
4303 my $ret = GetFieldAsInteger64List($self, $field);
4304 return wantarray ? @$ret : $ret;
4306 if ($type == $Geo::OGR::OFTRealList) {
4307 my $ret = GetFieldAsDoubleList($self, $field);
4308 return wantarray ? @$ret : $ret;
4310 if ($type == $Geo::OGR::OFTStringList) {
4311 my $ret = GetFieldAsStringList($self, $field);
4312 return wantarray ? @$ret : $ret;
4314 if ($type == $Geo::OGR::OFTBinary) {
4315 return GetFieldAsBinary($self, $field);
4317 if ($type == $Geo::OGR::OFTDate) {
4318 my @ret = GetFieldAsDateTime($self, $field);
4319 # year, month, day, hour, minute, second, timezone
4320 return wantarray ? @ret[0..2] : [@ret[0..2]];
4322 if ($type == $Geo::OGR::OFTTime) {
4323 my @ret = GetFieldAsDateTime($self, $field);
4324 return wantarray ? @ret[3..6] : [@ret[3..6]];
4326 if ($type == $Geo::OGR::OFTDateTime) {
4327 my @ret = GetFieldAsDateTime($self, $field);
4328 return wantarray ? @ret : [@ret];
4330 error(
"Perl bindings do not support the field type '".i2s(field_type => $type).
"'.");
4333 #** @method scalar GetFieldDefn($name)
4335 # Get the definition of a field.
4336 # @param name the name of the field.
4337 # @return a Geo::OGR::FieldDefn object.
4341 my $field = $self->GetFieldIndex(shift);
4342 return $self->GetFieldDefnRef($field);
4345 #** @method list GetFieldNames()
4347 # Get the names of the fields in this feature.
4352 #** @method scalar GetGeomFieldDefn($name)
4354 # Get the definition of a spatial field.
4355 # @param name the name of the spatial field.
4356 # @return a Geo::OGR::GeomFieldDefn object.
4358 sub GetGeomFieldDefn {
4360 my $field = $self->GetGeomFieldIndex(shift);
4361 return $self->GetGeomFieldDefnRef($field);
4364 #** @method GetNativeData()
4369 #** @method GetNativeMediaType()
4371 sub GetNativeMediaType {
4374 #** @method hash reference GetSchema()
4376 # @brief Get the schema of this feature.
4378 # @return the schema as a hash whose keywords are Name, StyleIgnored
4379 # and Fields. Fields is an anonymous array of first non-spatial and
4380 # then spatial field schemas as in Geo::OGR::FieldDefn::Schema() and
4381 # Geo::OGR::GeomFieldDefn::Schema().
4385 error(
"Schema of a feature cannot be set directly.") if @_;
4386 return $self->GetDefnRef->Schema;
4389 #** @method scalar GetStyleString()
4393 sub GetStyleString {
4396 #** @method IsFieldNull()
4401 #** @method IsFieldSetAndNotNull()
4403 sub IsFieldSetAndNotNull {
4406 #** @method Geo::OGR::Layer Layer()
4408 # @return the layer to which this feature belongs to or undef.
4415 #** @method hash reference Row(%row)
4417 # @note This method discards the data the destination feature (or
4418 # layer) does not support. Changes in data due to differences between
4419 # field types may also occur.
4421 # Get and/or set the data of the feature. The key of the (key,value)
4422 # pairs of the row is the field name. Special field names FID and
4423 # Geometry are used for feature id and (single) geometry
4424 # respectively. The geometry/ies is/are set and get using the
4425 # Geo::OGR::Feature::Geometry method. Field values are set using the
4426 # Geo::OGR::Feature::Field method.
4427 # @param row [optional] feature data in a hash.
4428 # @return a reference to feature data in a hash. Spatial fields are
4429 # returned as Geo::OGR::Geometry objects.
4433 my $nf = $self->GetFieldCount;
4434 my $ngf = $self->GetGeomFieldCount;
4437 if (@_ == 1 and ref($_[0]) eq
'HASH') {
4439 } elsif (@_ and @_ % 2 == 0) {
4442 error(
'Usage: $feature->Row(%FeatureData).');
4444 $self->SetFID($row{FID})
if defined $row{FID};
4445 #$self->Geometry($schema, $row{Geometry}) if $row{Geometry};
4446 for my $name (keys %row) {
4447 next
if $name eq
'FID';
4448 if ($name eq
'Geometry') {
4449 $self->Geometry(0, $row{$name});
4453 for my $i (0..$nf-1) {
4454 if ($self->GetFieldDefnRef($i)->Name eq $name) {
4455 $self->SetField($i, $row{$name});
4461 for my $i (0..$ngf-1) {
4462 if ($self->GetGeomFieldDefnRef($i)->Name eq $name) {
4463 $self->Geometry($i, $row{$name});
4469 carp
"Unknown field: '$name'.";
4472 return unless defined wantarray;
4474 for my $i (0..$nf-1) {
4475 my $name = $self->GetFieldDefnRef($i)->Name;
4476 $row{$name} = $self->GetField($i);
4478 for my $i (0..$ngf-1) {
4479 my $name = $self->GetGeomFieldDefnRef($i)->Name ||
'Geometry';
4480 $row{$name} = $self->GetGeometry($i);
4482 $row{FID} = $self->GetFID;
4486 #** @method SetFID($id)
4488 # @param id the feature id.
4493 #** @method SetField($name, @Value)
4499 my $field = $self->GetFieldIndex(shift);
4501 if (@_ == 0 or !defined($arg)) {
4502 _UnsetField($self, $field);
4505 $arg = [@_]
if @_ > 1;
4506 my $type = $self->GetFieldType($field);
4508 if ($type == $Geo::OGR::OFTIntegerList) {
4509 SetFieldIntegerList($self, $field, $arg);
4511 elsif ($type == $Geo::OGR::OFTInteger64List) {
4512 SetFieldInteger64List($self, $field, $arg);
4514 elsif ($type == $Geo::OGR::OFTRealList) {
4515 SetFieldDoubleList($self, $field, $arg);
4517 elsif ($type == $Geo::OGR::OFTStringList) {
4518 SetFieldStringList($self, $field, $arg);
4520 elsif ($type == $Geo::OGR::OFTDate) {
4521 _SetField($self, $field, @$arg[0..2], 0, 0, 0, 0);
4523 elsif ($type == $Geo::OGR::OFTTime) {
4525 _SetField($self, $field, 0, 0, 0, @$arg[0..3]);
4527 elsif ($type == $Geo::OGR::OFTDateTime) {
4529 _SetField($self, $field, @$arg[0..6]);
4531 elsif ($type == $Geo::OGR::OFTInteger64)
4533 SetFieldInteger64($self, $field, $arg);
4536 $type = i2s(field_type => $type);
4537 my $name = $self->GetFieldDefnRef($field)->Name;
4538 error(
"'$arg' is not a suitable value for field $name($type).");
4541 if ($type == $Geo::OGR::OFTBinary) {
4542 #$arg = unpack('H*', $arg); # remove when SetFieldBinary is available
4543 $self->SetFieldBinary($field, $arg);
4545 elsif ($type == $Geo::OGR::OFTInteger64)
4547 SetFieldInteger64($self, $field, $arg);
4549 elsif ($type == $Geo::OGR::OFTInteger or $type == $Geo::OGR::OFTReal or $type == $Geo::OGR::OFTString)
4551 _SetField($self, $field, $arg);
4554 $type = i2s(field_type => $type);
4555 my $name = $self->GetFieldDefnRef($field)->Name;
4556 error(
"'$arg' is not a suitable value for field $name($type).");
4561 #** @method SetFieldNull()
4566 #** @method SetFrom($other, $forgiving = 1, hashref map)
4568 # @param other a Geo::OGR::Feature object
4569 # @param forgiving [optional] set to false if the operation should not
4570 # continue if output fields do not match some of the source fields
4571 # @param map [optional] a mapping from output field indexes to source
4572 # fields, include into the hash all field indexes of this feature
4573 # which should be set
4576 my($self, $other) = @_;
4577 _SetFrom($self, $other),
return if @_ <= 2;
4578 my $forgiving = $_[2];
4579 _SetFrom($self, $other, $forgiving),
return if @_ <= 3;
4582 for my $i (1..GetFieldCount($self)) {
4583 push @list, ($map->{$i} || -1);
4585 SetFromWithMap($self, $other, 1, \@list);
4588 #** @method SetNativeData()
4593 #** @method SetNativeMediaType()
4595 sub SetNativeMediaType {
4598 #** @method SetStyleString($string)
4602 sub SetStyleString {
4605 #** @method list Tuple(@tuple)
4607 # @note This method discards the data the destination feature (or
4608 # layer) does not support. Changes in data due to differences between
4609 # field types may also occur.
4611 # @note The schema of the tuple needs to be the same as that of the
4614 # Get and/set the data of the feature. The expected data in the tuple
4615 # is ([feature_id,] non-spatial fields, spatial fields). The fields in
4616 # the tuple are in the order they are in the schema. Field values are
4617 # set using the Geo::OGR::Feature::Field method. Geometries are set
4618 # and get using the Geo::OGR::Feature::Geometry method.
4619 # @param tuple [optional] feature data in an array
4620 # @return feature data in an array
4624 my $nf = $self->GetFieldCount;
4625 my $ngf = $self->GetGeomFieldCount;
4627 my $values = ref $_[0] ? $_[0] : \@_;
4629 $FID = shift @$values
if @$values == $nf + $ngf + 1;
4630 $self->SetFID($FID)
if defined $FID;
4631 if (@$values != $nf + $ngf) {
4633 error(
"Too many or too few attribute values for a feature (need $n).");
4635 my $index = 0; # index to non-geometry and geometry fields
4636 for my $i (0..$nf-1) {
4637 $self->SetField($i, $values->[$i]);
4639 for my $i (0..$ngf-1) {
4640 $self->Geometry($i, $values->[$nf+$i]);
4643 return unless defined wantarray;
4644 my @ret = ($self->GetFID);
4645 for my $i (0..$nf-1) {
4646 my $v = $self->GetField($i);
4649 for my $i (0..$ngf-1) {
4650 my $v = $self->GetGeometry($i);
4656 #** @method scalar Validate(list flags)
4658 # @param flags one of more of null, geom_type, width,
4659 # allow_null_when_default, or all.
4660 # @exception croaks with an error message if the feature is not valid.
4661 # @return integer denoting the validity of the feature object.
4667 my $f = eval
'$Geo::OGR::'.uc($flag);
4670 _Validate($self, $flags);
4673 #** @method Geo::OGR::Feature new(%schema)
4675 # @brief Create a new feature.
4676 # @param Named parameters:
4677 # - \a Schema a reference to a schema hash, or a Geo::OGR::Layer,
4678 # Geo::OGR::Feature, or Geo::OGR::FeatureDefn object.
4679 # - \a Values values for the feature attributes.
4680 # - \a StyleIgnored whether the style can be omitted when fetching
4681 # features. (default is false)
4683 # Schema is a hash with the following keys:
4684 # - \a Name name of the schema (not used).
4685 # - \a Fields a list of Geo::OGR::FieldDefn or Geo::OGR::GeomFieldDefn
4686 # objects or references to hashes from which fields can be created.
4687 # - \a GeometryType the geometry type if the feature has only one spatial field.
4689 # @note Do not mix GeometryType and geometry fields in Fields list.
4690 # @note Old syntax where the argument is a Geo::OGR::FeatureDefn
4691 # object or Schema hash is supported.
4693 # @return a new Geo::OGR::Feature object.
4699 if (ref $_[0] eq
'HASH' && $_[0]->{Schema}) {
4702 $arg = {Schema => $_[0]};
4704 } elsif (@_ and @_ % 2 == 0) {
4706 unless ($arg->{Schema}) {
4708 $arg->{Schema} = \%tmp;
4711 error(
"The argument must be either a schema or a hash.");
4713 error(
"Missing schema.") unless $arg->{Schema};
4715 for (ref $arg->{Schema}) {
4717 $defn = $arg->{Schema}->GetDefn;
4721 $defn = $arg->{Schema};
4726 my $self = Geo::OGRc::new_Feature($defn);
4727 error(
"Feature creation failed.") unless $self;
4729 for (ref $arg->{Values}) {
4731 $self->Tuple($arg->{Values});
4735 $self->Row($arg->{Values});
4739 $self->
Tuple($arg->{Values}->Tuple);
4745 error(
"Value parameter must be an array, hash, or another feature. Not $_.");
4750 #** @class Geo::OGR::FeatureDefn
4751 # @brief The schema of a feature or a layer.
4752 # @details A FeatureDefn object is a collection of field definition objects. A
4753 # read-only FeatureDefn object can be obtained from a layer
4754 # (Geo::OGR::Layer::GetDefn()) or a feature
4755 # (Geo::OGR::Feature::GetDefn()).
4757 package Geo::OGR::FeatureDefn;
4761 #** @method AddField(%params)
4763 # @param params Named parameters to create a new Geo::OGR::FieldDefn
4764 # or Geo::OGR::GeomFieldDefn object.
4768 error(
"Read-only definition.")
if parent($self);
4771 } elsif (ref($_[0]) eq
'HASH') {
4773 } elsif (@_ % 2 == 0) {
4777 if (s_exists(field_type => $params{Type})) {
4779 $self->AddFieldDefn($fd);
4782 $self->AddGeomFieldDefn($fd);
4786 #** @method DeleteField($name)
4788 # @note Currently only geometry fields can be deleted.
4789 # @param index the index of the geometry field to be deleted.
4792 my ($self, $name) = @_;
4793 error(
"Read-only definition.")
if parent($self);
4794 for my $i (0..$self->GetFieldCount-1) {
4795 error(
"Non-spatial fields cannot be deleted.")
if $self->_GetFieldDefn($i)->Name eq $name;
4797 for my $i (0..$self->GetGeomFieldCount-1) {
4798 $self->DeleteGeomFieldDefn($i)
if $self->_GetGeomFieldDefn($i)->Name eq $name;
4800 error(2, $name,
'Field');
4803 #** @method Feature()
4807 return parent($self);
4810 #** @method scalar GetFieldDefn($name)
4812 # Get the definition of a field.
4813 # @param name the name of the field.
4814 # @return a Geo::OGR::FieldDefn object.
4818 my $field = $self->GetFieldIndex(shift);
4819 return $self->_GetFieldDefn($field);
4822 #** @method list GetFieldNames()
4824 # The names of the fields in this layer or feature definition.
4825 # @return the list of field names.
4830 for my $i (0..$self->GetFieldCount-1) {
4831 push @names, $self->_GetFieldDefn($i)->Name;
4833 for my $i (0..$self->GetGeomFieldCount-1) {
4834 push @names, $self->_GetGeomFieldDefn($i)->Name;
4839 #** @method scalar GetGeomFieldDefn($name)
4841 # Get the definition of a spatial field.
4842 # @param name the name of the spatial field.
4843 # @return a Geo::OGR::GeomFieldDefn object.
4845 sub GetGeomFieldDefn {
4847 my $field = $self->GetGeomFieldIndex(shift);
4848 return $self->_GetGeomFieldDefn($field);
4851 #** @method scalar GetName()
4853 # @return the name of this layer or feature definition.
4858 #** @method hash reference GetSchema()
4860 # @brief Get the schema of this feature or layer definition.
4862 # @return the schema as a hash whose keywords are Name, StyleIgnored
4863 # and Fields. Fields is an anonymous array of first non-spatial and
4864 # then spatial field schemas as in Geo::OGR::FieldDefn::Schema() and
4865 # Geo::OGR::GeomFieldDefn::Schema().
4869 carp
"Schema of a feature definition should not be set directly." if @_;
4870 if (@_ and @_ % 2 == 0) {
4872 if ($schema{Fields}) {
4873 for my $field (@{$schema{Fields}}) {
4874 $self->AddField($field);
4879 $schema{Name} = $self->Name();
4880 $schema{StyleIgnored} = $self->StyleIgnored();
4881 $schema{Fields} = [];
4882 for my $i (0..$self->GetFieldCount-1) {
4883 my $s = $self->_GetFieldDefn($i)->Schema;
4884 push @{$schema{Fields}}, $s;
4886 for my $i (0..$self->GetGeomFieldCount-1) {
4887 my $s = $self->_GetGeomFieldDefn($i)->Schema;
4888 push @{$schema{Fields}}, $s;
4890 return wantarray ? %schema : \%schema;
4893 #** @method IsSame(Geo::OGR::FeatureDefn defn)
4895 # @return true if this definition is similar to the other definition,
4901 #** @method scalar IsStyleIgnored()
4903 # Get the ignore status of style information when fetching features.
4904 # @return the ignore status of style information
4907 sub IsStyleIgnored {
4910 #** @method SetStyleIgnored($IgnoreState)
4912 # Set the ignore status of style information when fetching features.
4915 sub SetStyleIgnored {
4918 #** @method Geo::OGR::FeatureDefn new(%schema)
4920 # Creates a new layer or feature definition. The new definition is
4921 # either initialized to the given schema or it will contain no
4922 # non-spatial fields and one spatial field, whose Name is '' and
4923 # GeometryType is 'Unknown' or the value of the named parameter
4925 # @param schema [optional] The schema for the new feature definition,
4926 # as in Geo::OGR::FeatureDefn::Schema().
4927 # @return a Geo::OGR::FeatureDefn object
4931 # $fd = Geo::OGR::FeatureDefn->new(
4933 # Fields => [{ Name => 'field1', Type => 'String' },
4934 # { Name => 'geom', GeometryType => 'Point' }] );
4940 if (@_ == 1 and ref($_[0]) eq
'HASH') {
4942 } elsif (@_ and @_ % 2 == 0) {
4945 my $fields = $schema{Fields};
4946 error(
"The 'Fields' argument must be an array reference.")
if $fields and ref($fields) ne
'ARRAY';
4948 my $self = Geo::OGRc::new_FeatureDefn($schema{Name});
4950 my $gt = $schema{GeometryType};
4952 $self->GeometryType($gt);
4954 $self->DeleteGeomFieldDefn(0);
4956 $self->StyleIgnored($schema{StyleIgnored})
if exists $schema{StyleIgnored};
4957 for my $fd (@{$fields}) {
4959 if (ref($fd) eq
'HASH') {
4960 # if Name and Type are missing, assume Name => Type
4961 if (!(exists $fd->{Name} && exists $fd->{Type})) {
4962 for my $key (sort keys %$fd) {
4963 if (s_exists(field_type => $fd->{$key}) ||
4964 s_exists(geometry_type => $fd->{$key}))
4967 $fd->{Type} = $fd->{$key};
4973 if ($fd->{GeometryType} or ($fd->{Type} && s_exists(geometry_type => $fd->{Type}))) {
4979 if (blessed($d) and $d->isa(
'Geo::OGR::FieldDefn')) {
4980 AddFieldDefn($self, $d);
4981 } elsif (blessed($d) and $d->isa(
'Geo::OGR::GeomFieldDefn')) {
4982 error(
"Do not mix GeometryType and geometry fields in Fields.") if $gt;
4983 AddGeomFieldDefn($self, $d);
4985 error(
"Item in field list does not define a field.");
4991 #** @class Geo::OGR::FieldDefn
4992 # @brief A definition of a non-spatial attribute.
4995 package Geo::OGR::FieldDefn;
4999 #** @method scalar Default($value)
5001 # Get or set the default value for this field.
5002 # @note a.k.a. GetDefault and SetDefault
5003 # @param value [optional]
5004 # @return the default value of this field in non-void context.
5008 SetDefault($self, $_[0])
if @_;
5009 GetDefault($self)
if defined wantarray;
5012 #** @method GetSchema()
5017 #** @method scalar Ignored($ignore)
5019 # Get and/or set the ignore status (whether this field should be
5020 # omitted when fetching features) of this field.
5021 # @note a.k.a. IsIgnored, SetIgnored
5022 # @param ignore [optional]
5023 # @return the ignore status of this field in non-void context.
5028 SetIgnored($self, $_[0])
if @_;
5029 IsIgnored($self)
if defined wantarray;
5032 #** @method IsDefaultDriverSpecific()
5034 sub IsDefaultDriverSpecific {
5037 #** @method scalar Justify($justify)
5039 # Get and/or set the justification of this field.
5040 # @note a.k.a. GetJustify, SetJustify
5041 # @param justify [optional] One of field justify types (Geo::OGR::FieldDefn::JustifyValues).
5042 # @return the justify value of this field in non-void context.
5045 my($self, $justify) = @_;
5046 if (defined $justify) {
5047 $justify = s2i(justify => $justify);
5048 SetJustify($self, $justify);
5050 return i2s(justify => GetJustify($self))
if defined wantarray;
5053 #** @method list JustifyValues()
5054 # Package subroutine.
5055 # Justify values supported by GDAL. Current list is
5056 # Left, Right, and Undefined.
5062 #** @method scalar Name($name)
5064 # Get and/or set the name of the field.
5065 # @note a.k.a. GetName, GetNameRef, SetName
5066 # @param name [optional]
5067 # @return the name in non-void context
5071 SetName($self, $_[0])
if @_;
5072 GetName($self)
if defined wantarray;
5075 #** @method scalar Nullable($nullable)
5077 # Get or set the nullable constraint for this field.
5078 # @note a.k.a. IsNullable and SetNullable
5079 # @param nullable [optional]
5080 # @return the nullable value of this field in non-void context.
5084 SetNullable($self, $_[0])
if @_;
5085 IsNullable($self)
if defined wantarray;
5088 #** @method scalar Precision($precision)
5090 # Get and/or set the precision of this field.
5091 # @note a.k.a. GetPrecision, SetPrecision
5092 # @param precision [optional]
5093 # @return the precision of this field in non-void context.
5097 SetPrecision($self, $_[0])
if @_;
5098 GetPrecision($self)
if defined wantarray;
5101 #** @method hash reference Schema(%params)
5103 # Get the schema or set parts of the schema
5104 # @param params [optional] as those in Geo::OGR::FieldDefn::new.
5105 # @return a reference to a hash whose keys are as those in Geo::OGR::FieldDefn::new.
5110 my $params = @_ % 2 == 0 ? {@_} : shift;
5111 for my $key (keys %SCHEMA_KEYS) {
5112 next unless exists $params->{$key};
5113 eval
"\$self->$key(\$params->{$key})";
5114 confess(last_error()) if $@;
5117 return unless defined wantarray;
5119 for my $key (keys %SCHEMA_KEYS) {
5120 $schema{$key} = eval
'$self->'.$key;
5122 return wantarray ? %schema : \%schema;
5125 #** @method SetSchema()
5130 #** @method scalar SubType($SubType)
5132 # @note a.k.a. GetSubType, SetSubType
5133 # @param SubType [optional] One of field sub types (Geo::OGR::FieldDefn::SubTypes).
5134 # @return the sub type of this field in non-void context.
5137 my($self, $subtype) = @_;
5138 if (defined $subtype) {
5139 $subtype = s2i(field_subtype => $subtype);
5140 SetSubType($self, $subtype);
5142 return i2s(field_subtype => GetSubType($self))
if defined wantarray;
5145 #** @method SubTypes()
5151 #** @method scalar Type($type)
5153 # Get and/or set the type of the field.
5154 # @note a.k.a. GetFieldTypeName, GetTypeName, GetType, SetType
5155 # @param type [optional] One of field types (Geo::OGR::FieldDefn::Types).
5156 # @return one of field types in non-void context.
5159 my($self, $type) = @_;
5160 if (defined $type) {
5161 $type = s2i(field_type => $type);
5162 SetType($self, $type);
5164 return i2s(field_type => GetType($self))
if defined wantarray;
5167 #** @method list Types()
5168 # Package subroutine.
5169 # Field types supported by GDAL. Current list is
5170 # Binary, Date, DateTime, Integer, Integer64, Integer64List, IntegerList, Real, RealList, String, StringList, Time, WideString, and WideStringList.
5171 # (However, WideString is not supported.)
5177 #** @method scalar Width($width)
5179 # Get and/or set the field width.
5180 # @note a.k.a. GetWidth, SetWidth
5181 # @param width [optional]
5182 # @return the width of this field in non-void context.
5186 SetWidth($self, $_[0])
if @_;
5187 GetWidth($self)
if defined wantarray;
5190 #** @method Geo::OGR::FieldDefn new(%params)
5192 # @brief Create a new field definition.
5194 # @param Named parameters:
5195 # - \a Name Field name (default is 'unnamed').
5196 # - \a Type Field type, one of Geo::OGR::FieldDefn::Types (default is 'String').
5197 # - \a SubType Field sub type, one of Geo::OGR::FieldDefn::SubTypes.
5198 # - \a Justify Justify value, one of Geo::OGR::FieldDefn::JustifyValues
5201 # - \a Nullable (default is true)
5203 # - \a Ignored (default is false)
5205 # @note Simplified parameters Name => 'Type' are also supported.
5207 # @return a new Geo::OGR::FieldDefn object
5211 my $params = {Name =>
'unnamed', Type =>
'String'};
5213 } elsif (@_ == 1 and not ref $_[0]) {
5214 $params->{Name} = shift;
5215 } elsif (@_ == 2 and not $Geo::OGR::FieldDefn::SCHEMA_KEYS{$_[0]}) {
5216 $params->{Name} = shift;
5217 $params->{Type} = shift;
5219 my $tmp = @_ % 2 == 0 ? {@_} : shift;
5220 for my $key (keys %$tmp) {
5221 if ($Geo::OGR::FieldDefn::SCHEMA_KEYS{$key}) {
5222 $params->{$key} = $tmp->{$key};
5224 carp
"Unknown parameter: '$key'." if $key ne
'Index';
5228 $params->{Type} = s2i(field_type => $params->{Type});
5229 my $self = Geo::OGRc::new_FieldDefn($params->{Name}, $params->{Type});
5231 delete $params->{Name};
5232 delete $params->{Type};
5233 $self->Schema($params);
5237 #** @class Geo::OGR::GeomFieldDefn
5238 # @brief A definition of a spatial attribute.
5241 package Geo::OGR::GeomFieldDefn;
5245 #** @method scalar GeometryType($type)
5247 # @note a.k.a. GetType, SetType
5248 # @return the geometry type of the field.
5253 #** @method GetSchema()
5258 #** @method scalar Ignored($ignore)
5260 # @note a.k.a. IsIgnored, SetIgnored
5261 # @return the ignore status of the field.
5265 SetIgnored($self, $_[0])
if @_;
5266 IsIgnored($self)
if defined wantarray;
5269 #** @method scalar Name($name)
5271 # @note a.k.a. GetName, GetNameRef, SetName
5272 # @return the name of the field.
5276 SetName($self, $_[0])
if @_;
5277 GetName($self)
if defined wantarray;
5280 #** @method scalar Nullable($nullable)
5282 # @note a.k.a. IsNullable, SetNullable
5283 # @return the nullable status of the field.
5287 SetNullable($self, $_[0])
if @_;
5288 IsNullable($self)
if defined wantarray;
5291 #** @method hash reference Schema(%params)
5293 # Get the schema or set parts of the schema.
5294 # @param params [optional] as those in Geo::OGR::GeomFieldDefn::new.
5295 # @return a reference to a hash whose keys are as those in Geo::OGR::GeomFieldDefn::new.
5300 my $params = @_ % 2 == 0 ? {@_} : shift;
5301 for my $key (keys %SCHEMA_KEYS) {
5302 next unless exists $params->{$key};
5303 eval
"\$self->$key(\$params->{$key})";
5304 confess last_error() if $@;
5307 return unless defined wantarray;
5309 for my $key (keys %SCHEMA_KEYS) {
5310 $schema{$key} = eval
'$self->'.$key;
5312 return wantarray ? %schema : \%schema;
5315 #** @method SetSchema()
5320 #** @method scalar SpatialReference($sr)
5322 # @note a.k.a. GetSpatialRef, SetSpatialRef
5323 # @return the spatial reference of the field as a Geo::OSR::SpatialReference object.
5325 sub SpatialReference {
5327 SetSpatialRef($self, $_[0])
if @_;
5328 GetSpatialRef($self)
if defined wantarray;
5333 # @return the type of this geometry field. One of Geo::OGR::GeomFieldDefn::Types
5336 my($self, $type) = @_;
5337 if (defined $type) {
5338 $type = s2i(geometry_type => $type);
5339 SetType($self, $type);
5341 i2s(geometry_type => GetType($self))
if defined wantarray;
5345 # Package subroutine.
5346 # @return a list of all geometry types, currently:
5347 # CircularString, CircularStringM, CircularStringZ, CircularStringZM, CompoundCurve, CompoundCurveM, CompoundCurveZ, CompoundCurveZM, Curve, CurveM, CurvePolygon, CurvePolygonM, CurvePolygonZ, CurvePolygonZM, CurveZ, CurveZM, GeometryCollection, GeometryCollection25D, GeometryCollectionM, GeometryCollectionZM, LineString, LineString25D, LineStringM, LineStringZM, LinearRing, MultiCurve, MultiCurveM, MultiCurveZ, MultiCurveZM, MultiLineString, MultiLineString25D, MultiLineStringM, MultiLineStringZM, MultiPoint, MultiPoint25D, MultiPointM, MultiPointZM, MultiPolygon, MultiPolygon25D, MultiPolygonM, MultiPolygonZM, MultiSurface, MultiSurfaceM, MultiSurfaceZ, MultiSurfaceZM, None, Point, Point25D, PointM, PointZM, Polygon, Polygon25D, PolygonM, PolygonZM, PolyhedralSurface, PolyhedralSurfaceM, PolyhedralSurfaceZ, PolyhedralSurfaceZM, Surface, SurfaceM, SurfaceZ, SurfaceZM, TIN, TINM, TINZ, TINZM, Triangle, TriangleM, TriangleZ, TriangleZM, and Unknown.
5353 #** @method Geo::OGR::GeomFieldDefn new(%params)
5355 # @brief Create a new spatial field definition.
5357 # @param params one or more of:
5358 # - \a Name name for the field (default is 'geom').
5359 # - \a GeometryType type for the field type, one of Geo::OGR::GeomFieldDefn::Types (default is 'Unknown').
5360 # - \a SpatialReference a Geo::OSR::SpatialReference object.
5361 # - \a Nullable (default is true)
5362 # - \a Ignored (default is false)
5364 # @note Simplified parameters <name> => <type> is also supported.
5366 # @return a new Geo::OGR::GeomFieldDefn object
5370 my $params = {Name =>
'geom', Type =>
'Unknown'};
5373 $params->{Name} = shift;
5374 } elsif (@_ == 2 and not $Geo::OGR::GeomFieldDefn::SCHEMA_KEYS{$_[0]}) {
5375 $params->{Name} = shift;
5376 $params->{Type} = shift;
5378 my $tmp = @_ % 2 == 0 ? {@_} : shift;
5379 for my $key (keys %$tmp) {
5380 if ($Geo::OGR::GeomFieldDefn::SCHEMA_KEYS{$key}) {
5381 $params->{$key} = $tmp->{$key};
5383 carp
"Unknown parameter: '$key'." if $key ne
'Index' && $key ne
'GeometryType';
5388 $params->{Type} = s2i(geometry_type => $params->{Type});
5389 my $self = Geo::OGRc::new_GeomFieldDefn($params->{Name}, $params->{Type});
5391 delete $params->{Name};
5392 delete $params->{Type};
5393 $self->Schema($params);
5397 #** @class Geo::OGR::Geometry
5398 # @brief Spatial data.
5399 # @details A geometry is spatial data (coordinate values, and a reference to a
5400 # spatial reference system) organized into one of the geometry
5401 # types. Geometries can be created from several type of data including
5402 # a Perl data structure. There are several methods, which modify,
5403 # compare, test, or compute values from geometries.
5404 # @note Most spatial analysis methods require <a
5405 # href="http://geos.osgeo.org/doxygen/">GEOS</a> to work rigorously.
5407 package Geo::OGR::Geometry;
5411 #** @method AddGeometry($other)
5413 # Add a copy of another geometry to a geometry collection
5414 # @param other a Geo::OGR::Geometry object
5419 #** @method AddGeometryDirectly($other)
5421 # @param other a Geo::OGR::Geometry object
5423 sub AddGeometryDirectly {
5426 #** @method AddPoint($x, $y, $z)
5428 # Set the data of a point or add a point to a line string. Consider
5429 # using Geo::OGR::Geometry::Points. Note that the coordinate
5430 # dimension is automatically upgraded to 25D (3) if z is given.
5433 # @param z [optional]
5434 # Calls internally the 2D or 3D version depending on the number of parameters.
5438 my $t = $self->GetGeometryType;
5439 my $has_z = HasZ($t);
5440 my $has_m = HasM($t);
5441 if (!$has_z && !$has_m) {
5442 $self->AddPoint_2D(@_[0..1]);
5443 } elsif ($has_z && !$has_m) {
5444 $self->AddPoint_3D(@_[0..2]);
5445 } elsif (!$has_z && $has_m) {
5446 $self->AddPointM(@_[0..2]);
5448 $self->AddPointZM(@_[0..3]);
5452 #** @method AddPointM()
5457 #** @method AddPointZM()
5462 #** @method AddPoint_2D($x, $y)
5464 # Set the data of a point or add a point to a line string. Consider
5465 # using Geo::OGR::Geometry::Points.
5472 #** @method AddPoint_3D($x, $y, $z)
5474 # Set the data of a point or add a point to a line string. Note that
5475 # the coordinate dimension is automatically upgraded to 25D (3). Consider
5476 # using Geo::OGR::Geometry::Points.
5484 #** @method Geo::OGR::Geometry ApproximateArcAngles(%params)
5485 # Package subroutine.
5486 # Create a line string, which approximates an arc.
5487 # @note All angles are in degrees.
5489 # @param %params Named parameters:
5490 # - \a Center center point (default is [0, 0, 0])
5491 # - \a PrimaryRadius default is 1.
5492 # - \a SecondaryAxis default is 1.
5493 # - \a Rotation default is 0.
5494 # - \a StartAngle default is 0.
5495 # - \a EndAngle default is 360.
5496 # - \a MaxAngleStepSizeDegrees default is 4.
5497 # @return a new Geo::OGR::Geometry object.
5499 sub ApproximateArcAngles {
5501 my %
default = ( Center => [0,0,0],
5507 MaxAngleStepSizeDegrees => 4
5509 for my $p (keys %p) {
5510 if (exists $default{$p}) {
5513 carp
"Unknown parameter: '$p'.";
5516 for my $p (keys %
default) {
5519 error(
"Usage: Center => [x,y,z].") unless ref($p{Center}) eq
'ARRAY';
5523 return Geo::OGR::ApproximateArcAngles($p{Center}->[0], $p{Center}->[1], $p{Center}->[2], $p{PrimaryRadius}, $p{SecondaryAxis}, $p{Rotation}, $p{StartAngle}, $p{EndAngle}, $p{MaxAngleStepSizeDegrees});
5526 #** @method scalar Area()
5528 # @note a.k.a. GetArea
5529 # @return the area of the polygon or multipolygon
5534 #** @method scalar As(%params)
5536 # Export the geometry into a known format.
5538 # @param params Named parameters:
5539 # - \a Format One of
5540 # - \a WKT Well Known Text.
5541 # - <em>ISO WKT</em>
5542 # - \a Text Same as WKT.
5543 # - \a WKB Well Known Binary.
5544 # - <em>ISO WKB</em>
5545 # - \a Binary Same as WKB.
5550 # - \a ByteOrder Byte order for binary formats. Default is 'XDR'.
5551 # - \a SRID Spatial reference id for HEXEWKB.
5552 # - \a Options GML generation options.
5553 # - \a AltitudeMode For KML.
5555 # @return the geometry in a given format.
5559 my $p = named_parameters(\@_, Format => undef, ByteOrder =>
'XDR', SRID => undef, Options => undef, AltitudeMode => undef);
5560 my $f = $p->{format};
5561 if ($f =~ /text/i) {
5562 return $self->AsText;
5563 } elsif ($f =~ /wkt/i) {
5565 return $self->ExportToIsoWkt;
5567 return $self->AsText;
5569 } elsif ($f =~ /binary/i) {
5570 return $self->ExportToWkb($p->{byteorder});
5571 } elsif ($f =~ /wkb/i) {
5573 $p->{byteorder} = s2i(byte_order => $p->{byteorder});
5574 return $self->ExportToIsoWkb($p->{byteorder});
5575 } elsif ($f =~ /ewkb/i) {
5576 return $self->AsHEXEWKB($p->{srid});
5577 } elsif ($f =~ /hex/i) {
5578 return $self->AsHEXWKB;
5580 return $self->ExportToWkb($p->{byteorder});
5582 } elsif ($f =~ /gml/i) {
5583 return $self->ExportToGML($p->{options});
5584 } elsif ($f =~ /kml/i) {
5585 return $self->ExportToKML($p->{altitudemode});
5586 } elsif ($f =~ /json/i) {
5587 return $self->AsJSON;
5589 error(1, $f, map {$_=>1} qw/Text WKT ISO_WKT ISO_WKB HEX_WKB HEX_EWKB Binary GML KML JSON/);
5593 #** @method scalar AsBinary()
5595 # Export the geometry into WKB.
5596 # @sa Geo::OGR::Geometry::As
5597 # @return the geometry as WKB.
5602 #** @method scalar AsText()
5604 # Export the geometry into WKT.
5605 # @sa Geo::OGR::Geometry::As
5606 # @return the geometry as WKT.
5611 #** @method AssignSpatialReference($srs)
5613 # @param srs a Geo::OSR::SpatialReference object
5615 sub AssignSpatialReference {
5618 #** @method Geo::OGR::Geometry Boundary()
5620 # @note a.k.a. GetBoundary
5621 # @return the boundary of this geometry as a geometry
5627 #** @method Geo::OGR::Geometry Buffer($distance, $quadsecs = 30)
5631 # @return a new Geo::OGR::Geometry object
5636 #** @method Geo::OGR::Geometry BuildPolygonFromEdges($BestEffort = 0, $AutoClose = 0, $Tolerance = 0)
5638 # Attempt to create a polygon from a collection of lines or from a multilinestring.
5639 # @param BestEffort For future
5640 # @param AutoClose Assure the first and last points of rings are same.
5641 # @param Tolerance Snap distance.
5642 # @exception Several possibilities, some are reported, some are general errors.
5643 # @return a new Geo::OGR::Geometry object (Polygon)
5645 sub BuildPolygonFromEdges {
5648 #** @method list ByteOrders()
5649 # Package subroutine.
5650 # Same as Geo::OGR::ByteOrders
5653 return @BYTE_ORDER_TYPES;
5656 #** @method Geo::OGR::Geometry Centroid()
5658 # @return a new Geo::OGR::Geometry object
5664 #** @method Geo::OGR::Geometry Clone()
5666 # @return a new Geo::OGR::Geometry object
5671 #** @method CloseRings()
5677 #** @method Geo::OGR::Geometry Collect(@geometries)
5679 # Create a geometrycollection from this and possibly other geometries.
5680 # @param geometries [optional] More geometries to add to the collection.
5681 # @return a new Geo::OGR::Geometry object of type geometrycollection.
5686 #** @method scalar Contains($other)
5688 # @param other a Geo::OGR::Geometry object
5689 # @return true if this geometry contains the other geometry, false otherwise
5694 #** @method Geo::OGR::Geometry ConvexHull()
5696 # @return a new Geo::OGR::Geometry object
5701 #** @method scalar CoordinateDimension($dimension)
5703 # @param dimension [optional]
5706 sub CoordinateDimension {
5708 SetCoordinateDimension($self, $_[0])
if @_;
5709 GetCoordinateDimension($self)
if defined wantarray;
5712 #** @method scalar Crosses($other)
5714 # @param other a Geo::OGR::Geometry object
5715 # @return true if this geometry crosses the other geometry, false otherwise
5720 #** @method DelaunayTriangulation()
5722 sub DelaunayTriangulation {
5725 #** @method Geo::OGR::Geometry Difference($other)
5727 # @param other a Geo::OGR::Geometry object
5728 # @return a new Geo::OGR::Geometry object
5733 #** @method scalar Disjoint($other)
5735 # @param other a Geo::OGR::Geometry object
5736 # @return true if this geometry is disjoint from the other geometry, false otherwise
5741 #** @method list Dissolve()
5743 # Dissolve a geometrycollection into separate geometries.
5744 # @return a list of new Geo::OGR::Geometry objects cloned from the collection.
5749 my $n = $self->GetGeometryCount;
5751 for my $i (0..$n-1) {
5752 push @c, $self->GetGeometryRef($i)->Clone;
5760 #** @method scalar Distance($other)
5762 # @param other a Geo::OGR::Geometry object
5763 # @return the distance to the other geometry
5768 #** @method Distance3D()
5775 # Clear geometry data, i.e., remove all points, or, for a point, set
5776 # the coordinate dimension as zero.
5781 #** @method scalar Equals($other)
5783 # @note a.k.a. Equal (deprecated)
5784 # @param other a Geo::OGR::Geometry object
5785 # @return true if this geometry is equivalent to the other geometry, false otherwise
5790 #** @method Extent()
5797 #** @method Feature()
5804 #** @method FlattenTo2D()
5810 #** @method Geo::OGR::Geometry ForceTo($type, ref options)
5812 # Attempt to make a geometry of type 'type' out of this geometry.
5813 # @param type target geometry type. One of Geo::OGR::GeometryTypes.
5814 # @param options not used currently.
5815 # @return a new Geo::OGR::Geometry object.
5820 $type = s2i(geometry_type => $type);
5822 $self = Geo::OGR::ForceTo($self, $type, @_);
5824 confess last_error() if $@;
5828 #** @method Geo::OGR::Geometry ForceToCollection(@geometries)
5830 # Create a geometrycollection from the geometry.
5831 # @param geometries [optional] More geometries to add to the collection.
5832 # @return a new Geo::OGR::Geometry object of type geometrycollection.
5834 sub ForceToCollection {
5842 #** @method Geo::OGR::Geometry ForceToLineString()
5844 # Attempt to create a line string from this geometry.
5845 # @return a new Geo::OGR::Geometry object.
5847 sub ForceToLineString {
5849 return Geo::OGR::ForceToLineString($self);
5852 #** @method Geo::OGR::Geometry ForceToMultiLineString(@linestrings)
5854 # Attempt to create a multilinestring from the geometry, which must be a linestring.
5855 # @param linestrings [optional] More linestrings to add to the collection.
5856 # @return a new Geo::OGR::Geometry object of type multilinestring.
5858 sub ForceToMultiLineString {
5860 $self = Geo::OGR::ForceToMultiLineString($self);
5862 $self->AddGeometry($g);
5867 #** @method Geo::OGR::Geometry ForceToMultiPoint(@points)
5869 # Attempt to create a multipoint from the geometry, which must be a point.
5870 # @param points [optional] More points to add to the collection.
5871 # @return a new Geo::OGR::Geometry object of type multipoint.
5873 sub ForceToMultiPoint {
5875 $self = Geo::OGR::ForceToMultiPoint($self);
5877 $self->AddGeometry($g);
5882 #** @method Geo::OGR::Geometry ForceToMultiPolygon(@polygons)
5884 # Attempt to create a multipolygon from the geometry, which must be a polygon.
5885 # @param polygons [optional] More polygons to add to the collection.
5886 # @return a new Geo::OGR::Geometry object of type multipolygon.
5888 sub ForceToMultiPolygon {
5890 $self = Geo::OGR::ForceToMultiPolygon($self);
5892 $self->AddGeometry($g);
5897 #** @method Geo::OGR::Geometry ForceToPolygon()
5899 # Attempt to create a polygon from this geometry.
5900 # @exception None reported. If this method fails, just a copy is returned.
5901 # @return a new Geo::OGR::Geometry object.
5903 sub ForceToPolygon {
5906 #** @method scalar Geometry($n)
5908 # Return the n:th (note zero-based index) element in this geometry or
5909 # geometry in this collection.
5910 # @note a.k.a. GetGeometryRef
5911 # @param n index to the geometry, which is a part of this geometry
5912 # @return a new Geo::OGR::Geometry object whose data is a part of the
5913 # parent geometry (this geometry is kept alive while the returned
5919 #** @method scalar GeometryCount()
5921 # Return the number of elements in this geometry or geometries in this collection.
5922 # @note a.k.a. GetGeometryCount
5923 # @return an integer
5928 #** @method scalar GeometryType()
5931 # @note The deprecated method GetGeometryType returns the
5932 # type as an integer
5934 # @return the geometry type of this geometry (one of Geo::OGR::GeometryTypes).
5938 return i2s(geometry_type => $self->GetGeometryType);
5941 #** @method list GeometryTypes()
5942 # Package subroutine.
5943 # Same as Geo::OGR::GeometryTypes
5946 return @GEOMETRY_TYPES;
5949 #** @method scalar GetCoordinateDimension()
5951 # @return an integer
5953 sub GetCoordinateDimension {
5956 #** @method GetCurveGeometry()
5958 sub GetCurveGeometry {
5961 #** @method scalar GetDimension()
5963 # @return 0, 1, or 2
5968 #** @method list GetEnvelope()
5970 # @note In scalar context returns a reference to an anonymous array
5971 # containing the envelope.
5972 # @return the envelope ($minx, $maxx, $miny, $maxy)
5977 #** @method list GetEnvelope3D()
5979 # @note In scalar context returns a reference to an anonymous array
5980 # containing the envelope.
5981 # @return the 3-D envelope ($minx, $maxx, $miny, $maxy, $minz, $maxz)
5987 #** @method scalar GetGeometryRef($index)
5989 # @deprecated Use Geo::OGR::Geometry
5991 sub GetGeometryRef {
5992 my ($self, $i) = @_;
5993 my $ref = $self->_GetGeometryRef($i);
5998 #** @method GetLinearGeometry()
6000 sub GetLinearGeometry {
6008 #** @method list GetPoint($index = 0)
6011 # @return (x,y) or a list with more coordinates
6016 my $t = $self->GetGeometryType;
6017 my $has_z = HasZ($t);
6018 my $has_m = HasM($t);
6020 if (!$has_z && !$has_m) {
6021 $point = $self->GetPoint_2D($i);
6022 } elsif ($has_z && !$has_m) {
6023 $point = $self->GetPoint_3D($i);
6024 } elsif (!$has_z && $has_m) {
6025 $point = $self->GetPointZM($i);
6026 @$point = ($point->[0], $point->[1], $point->[3]);
6028 $point = $self->GetPointZM($i);
6030 return wantarray ? @$point : $point;
6033 #** @method scalar GetPointCount()
6035 # @return an integer
6040 #** @method GetPointZM()
6045 #** @method scalar GetPoint_2D($index = 0)
6048 # @return (x,y) or a list with more coordinates
6053 #** @method scalar GetPoint_3D($index = 0)
6056 # @return (x,y) or a list with more coordinates
6061 #** @method Geo::OSR::SpatialReference GetSpatialReference()
6063 # @return a new Geo::OSR::SpatialReference object
6065 sub GetSpatialReference {
6068 #** @method scalar GetX($index = 0)
6076 #** @method scalar GetY($index = 0)
6084 #** @method scalar GetZ($index = 0)
6092 #** @method HasCurveGeometry()
6094 sub HasCurveGeometry {
6097 #** @method Geo::OGR::Geometry Intersection($other)
6099 # @param other a Geo::OGR::Geometry object
6100 # @return a new Geo::OGR::Geometry object
6105 #** @method scalar Intersects($other)
6107 # @note a.k.a. Intersect (deprecated)
6108 # @param other a Geo::OGR::Geometry object
6109 # @return true if this geometry intersects with the other geometry, false otherwise
6119 #** @method scalar IsEmpty()
6121 # Test whether the geometry is empty (has no points, or, for a point,
6122 # has coordinate dimension of zero).
6128 #** @method IsMeasured()
6133 #** @method scalar IsRing()
6135 # Test if the geometry is a ring. Requires GEOS in GDAL.
6141 #** @method scalar IsSimple()
6143 # Test the simplicity of the geometry (OGC sense). Requires GEOS in GDAL.
6149 #** @method scalar IsValid()
6151 # Test the validity of the geometry (OGC sense). Requires GEOS in GDAL.
6157 #** @method scalar Length()
6159 # @return the length of the linestring
6164 #** @method Move($dx, $dy, $dz)
6166 # Move every point of the object as defined by the parameters.
6169 # @param dz [optional]
6174 #** @method scalar Overlaps($other)
6176 # @param other a Geo::OGR::Geometry object
6177 # @return true if this geometry overlaps the other geometry, false otherwise
6182 #** @method list Point($index, $x, $y, $z)
6184 # Get or set the point
6185 # @param index The index of the point. Optional (ignored if given) for
6186 # Point and Point25D geometries.
6187 # @param x [optional]
6188 # @param y [optional]
6189 # @param z [optional]
6196 my $t = $self->GetGeometryType;
6198 if (Flatten($t) == $Geo::OGR::wkbPoint) {
6199 my $has_z = HasZ($t);
6200 my $has_m = HasM($t);
6201 if (!$has_z && !$has_m) {
6204 } elsif ($has_z || $has_m) {
6212 $i = shift unless defined $i;
6213 $self->SetPoint($i, @_);
6215 return unless defined wantarray;
6216 my $point = $self->GetPoint;
6217 return wantarray ? @$point : $point;
6220 #** @method PointOnSurface()
6222 sub PointOnSurface {
6225 #** @method array reference Points(arrayref points)
6227 # Get or set the points of the geometry. The points (vertices) are
6228 # stored in obvious lists of lists. When setting, the geometry is
6229 # first emptied. The method uses internally either AddPoint_2D or
6230 # AddPoint_3D depending on the coordinate dimension of the input data.
6232 # @note The same structure may represent different geometries
6233 # depending on the actual geometry type of the object.
6235 # @param points [optional] A reference to an array. A point is a reference to an
6236 # array of numbers, a linestring or a ring is a reference to an array of points,
6237 # a polygon is a reference to an array of rings, etc.
6239 # @return A reference to an array.
6243 my $t = $self->GetGeometryType;
6244 my $has_z = HasZ($t);
6245 my $has_m = HasM($t);
6247 $postfix .=
'Z' if HasZ($t);
6248 $postfix .=
'M' if HasM($t);
6249 $t = i2s(geometry_type => Flatten($t));
6253 if ($t eq
'Unknown' or $t eq
'None' or $t eq
'GeometryCollection') {
6254 error(
"Can't set points of a geometry of type '$t'.");
6255 } elsif ($t eq
'Point') {
6256 # support both "Point" as a list of one point and one point
6257 if (ref($points->[0])) {
6258 $self->AddPoint(@{$points->[0]});
6260 $self->AddPoint(@$points);
6262 } elsif ($t eq
'LineString' or $t eq
'LinearRing' or $t eq
'CircularString') {
6263 for my $p (@$points) {
6264 $self->AddPoint(@$p);
6266 } elsif ($t eq
'Polygon') {
6267 for my $r (@$points) {
6269 $ring->
Set3D(1)
if $has_z;
6270 $ring->SetMeasured(1)
if $has_m;
6272 $self->AddGeometryDirectly($ring);
6274 } elsif ($t eq
'MultiPoint') {
6275 for my $p (@$points) {
6278 $self->AddGeometryDirectly($point);
6280 } elsif ($t eq
'MultiLineString') {
6281 for my $l (@$points) {
6284 $self->AddGeometryDirectly($linestring);
6286 } elsif ($t eq
'MultiPolygon') {
6287 for my $p (@$points) {
6290 $self->AddGeometryDirectly($polygon);
6294 return unless defined wantarray;
6295 $self->_GetPoints();
6298 #** @method Polygonize()
6303 #** @method RemoveGeometry()
6305 sub RemoveGeometry {
6308 #** @method Segmentize($MaxLength)
6310 # Modify the geometry such it has no segment longer than the given length.
6311 # @param MaxLength the given length
6321 #** @method SetCoordinateDimension($dimension)
6325 sub SetCoordinateDimension {
6328 #** @method SetMeasured()
6333 #** @method SetPoint($index, $x, $y, $z)
6335 # Set the data of a point or a line string. Note that the coordinate
6336 # dimension is automatically upgraded to 25D (3) if z is given.
6340 # @param z [optional]
6344 my $t = $self->GetGeometryType;
6345 my $has_z = HasZ($t);
6346 my $has_m = HasM($t);
6347 if (!$has_z && !$has_m) {
6348 $self->SetPoint_2D(@_[0..2]);
6349 } elsif ($has_z && !$has_m) {
6350 $self->SetPoint_3D(@_[0..3]);
6351 } elsif (!$has_z && $has_m) {
6352 $self->SetPointM(@_[0..3]);
6354 $self->SetPointZM(@_[0..4]);
6358 #** @method SetPointM()
6363 #** @method SetPointZM()
6368 #** @method SetPoint_2D($index, $x, $y)
6377 #** @method SetPoint_3D($index, $x, $y, $z)
6379 # Set the data of a point or a line string. Note that the coordinate
6380 # dimension is automatically upgraded to 25D (3).
6389 #** @method Geo::OGR::Geometry Simplify($Tolerance)
6391 # Simplify the geometry.
6392 # @param Tolerance the length tolerance for the simplification
6394 # @return a new Geo::OSR::Geometry object
6399 #** @method SimplifyPreserveTopology()
6401 sub SimplifyPreserveTopology {
6404 #** @method SwapXY()
6409 #** @method Geo::OGR::Geometry SymDifference($other)
6411 # Compute symmetric difference.
6412 # @note a.k.a. SymmetricDifference
6413 # @param other a Geo::OGR::Geometry object
6414 # @return a new Geo::OGR::Geometry object
6420 #** @method scalar Touches($other)
6422 # @param other a Geo::OGR::Geometry object
6423 # @return true if this geometry touches the other geometry, false otherwise
6428 #** @method Transform($trans)
6430 # @param trans a Geo::OSR::CoordinateTransformation object
6435 #** @method TransformTo($srs)
6437 # @param srs a Geo::OSR::SpatialReference object
6442 #** @method Geo::OGR::Geometry Union($other)
6444 # @param other a Geo::OGR::Geometry object
6445 # @return a new Geo::OGR::Geometry object
6450 #** @method Geo::OGR::Geometry UnionCascaded()
6452 # @return a new Geo::OGR::Geometry object
6463 #** @method scalar Within($other)
6465 # @param other a Geo::OGR::Geometry object
6466 # @return true if this geometry is within the other geometry, false otherwise
6471 #** @method scalar WkbSize()
6473 # @return an integer
6478 #** @method Geo::OGR::Geometry new(%params)
6480 # @param %params A named parameter, one of:
6481 # - \a GeometryType one the supported geometry types, see Geo::OGR::GeometryTypes.
6482 # - \a WKT a well known text string, which defines a geometry.
6483 # - \a WKB a well known binary string, which defines a geometry.
6484 # - \a HEXWKB WKB in hexadecimal.
6485 # - \a HEXEWKB PostGIS extended WKB.
6486 # - \a GML geometry written in Geographic Markup Language.
6487 # - \a GeoJSON geometry written in GeoJSON (JavaScript Object Notation for Geographic data).
6488 # - \a arc a reference to a list of values defining an arc: [CenterX,
6489 # CenterY, CenterZ, PrimaryRadius, SecondaryRadius, Rotation,
6490 # StartAngle, EndAngle, MaxAngleStepSizeDegrees] (see also Geo::OGR::Geometry::ApproximateArcAngles)
6491 # - \a Points An anonymous array as in method
6492 # Geo::OGR::Geometry::Points; Note: requires also GeometryType
6495 # @return a new Geo::OGR::Geometry object.
6500 if (@_ == 1 and ref($_[0]) eq
'HASH') {
6502 } elsif (@_ % 2 == 0) {
6505 ($param{GeometryType}) = @_;
6507 my $type = $param{GeometryType}
6508 my $srs = $param{SRS}
6509 my $wkt = $param{WKT}
6510 my $wkb = $param{WKB}
6511 my $hex = $param{HEXEWKB}
6514 # EWKB contains SRID
6515 $srid = substr($hex, 10, 8);
6516 substr($hex, 10, 8) =
'';
6518 $hex = $param{HEXWKB}
6522 for (my $i = 0; $i < length($hex); $i+=2) {
6523 $wkb .= chr(hex(substr($hex,$i,2)));
6526 my $gml = $param{GML}
6527 my $json = $param{GeoJSON}
6528 my $points = $param{Points}
6529 my $arc = $param{Arc}
6532 $self = Geo::OGRc::CreateGeometryFromWkt($wkt, $srs);
6533 } elsif (defined $wkb) {
6534 $self = Geo::OGRc::CreateGeometryFromWkb($wkb, $srs);
6535 } elsif (defined $gml) {
6536 $self = Geo::OGRc::CreateGeometryFromGML($gml);
6537 } elsif (defined $json) {
6538 $self = Geo::OGRc::CreateGeometryFromJson($json);
6539 } elsif (defined $type) {
6540 $type = s2i(geometry_type => $type);
6541 $self = Geo::OGRc::new_Geometry($type); # flattens the type
6542 $self->Set3D(1)
if HasZ($type);
6543 $self->SetMeasured(1)
if HasM($type);
6544 } elsif (defined $arc) {
6545 $self = Geo::OGRc::ApproximateArcAngles(@$arc);
6547 error(1, undef, map {$_=>1} qw/GeometryType WKT WKB HEXEWKB HEXWKB GML GeoJSON Arc/);
6549 bless $self, $pkg
if defined $self;
6550 $self->Points($points)
if $points;
6554 #** @class Geo::OGR::Layer
6555 # @brief A collection of similar features.
6556 # @details A layer object is typically obtained with a data source object. A
6557 # layer has a data model (a schema), which is maintained in a
6558 # definition object, and a set of features, which contain data
6559 # according to the data model. The schema is typically set when the
6560 # layer is created or opened, but it may be altered somewhat with
6561 # methods Geo::OGR::Layer::CreateField,
6562 # Geo::OGR::Layer::AlterFieldDefn, and
6563 # Geo::OGR::Layer::DeleteField. Features and/or their data can be
6564 # read, inserted and deleted. Reading can be filtered. Layers can be
6565 # compared to each other with methods Clip, Erase, Identity,
6566 # Intersection, SymDifference, Union, and Update.
6567 # A layer may have metadata OLMD_FID64 => 'YES' if it holds features
6568 # with 64 bit FIDs. The metadata of a layer can be obtained with
6569 # GetMetadata method.
6571 package Geo::OGR::Layer;
6575 #** @method AlterFieldDefn($name, %params)
6577 # @param field the name of the field to be altered.
6578 # @param params as in Geo::OGR::FieldDefn::new. Width and
6579 # Precision should be both or neither.
6580 # @note Only non-spatial fields can be altered.
6581 # @note Also the deprecated form AlterFieldDefn($field,
6582 # Geo::OGR::FieldDefn $Defn, $Flags) works.
6584 sub AlterFieldDefn {
6586 my $index = $self->GetLayerDefn->GetFieldIndex(shift
6587 my $param = @_ % 2 == 0 ? {@_} : shift;
6588 if (blessed($param) and $param->isa(
'Geo::OGR::FieldDefn')) {
6589 _AlterFieldDefn($self, $index, @_);
6591 my $definition = Geo::OGR::FieldDefn->new($param);
6593 $flags |= 1 if exists $param->{Name};
6594 $flags |= 2
if exists $param->{Type};
6595 $flags |= 4
if exists $param->{Width} or exists $param->{Precision};
6596 $flags |= 8
if exists $param->{Nullable};
6597 $flags |= 16
if exists $param->{Default};
6598 _AlterFieldDefn($self, $index, $definition, $flags);
6602 #** @method list Capabilities()
6604 # Both a package subroutine and an object method.
6605 # @return a list of capabilities. The object method returns a list of
6606 # the capabilities the layer has. The package subroutine returns a list of
6607 # all potential capabilities a layer may have. These are currently:
6608 # AlterFieldDefn, CreateField, CreateGeomField, CurveGeometries, DeleteFeature, DeleteField, FastFeatureCount, FastGetExtent, FastSetNextByIndex, FastSpatialFilter, IgnoreFields, MeasuredGeometries, RandomRead, RandomWrite, ReorderFields, SequentialWrite, StringsAsUTF8, and Transactions.
6612 # @cap = Geo::OGR::Layer::Capabilities(); # the package subroutine
6613 # @cap = $layer->Capabilities(); # the object method
6617 return @CAPABILITIES
if @_ == 0;
6620 for my $cap (@CAPABILITIES) {
6621 push @cap, $cap
if _TestCapability($self, $CAPABILITIES{$cap});
6626 #** @method Clip(Geo::OGR::Layer method, Geo::OGR::Layer result, hashref options, coderef callback, $callback_data)
6628 # Clip off areas that are not covered by the method layer. The schema
6629 # of the result layer can be set before calling this method, or is
6630 # initialized to to contain all fields from
6631 # this and method layer.
6632 # @param method method layer.
6633 # @param result result layer.
6634 # @param options a reference to an options hash.
6635 # @param callback [optional] a reference to a subroutine, which will
6636 # be called with parameters (number progress, string msg, callback_data)
6637 # @param callback_data [optional]
6642 #** @method CommitTransaction()
6645 sub CommitTransaction {
6648 #** @method CreateFeature()
6653 #** @method CreateField(%params)
6656 # @param params as in Geo::OGR::FieldDefn::new or
6657 # Geo::OGR::GeomFieldDefn::new, plus ApproxOK (whose default is true).
6661 my %defaults = ( ApproxOK => 1,
6665 } elsif (ref($_[0]) eq
'HASH') {
6667 } elsif (@_ % 2 == 0) {
6670 ($params{Defn}) = @_;
6672 for my $k (keys %defaults) {
6675 if (blessed($params{Defn}) and $params{Defn}->isa(
'Geo::OGR::FieldDefn')) {
6676 $self->_CreateField($params{Defn}, $params{ApproxOK});
6677 } elsif (blessed($_[0]) and $params{Defn}->isa(
'Geo::OGR::GeomFieldDefn')) {
6678 $self->CreateGeomField($params{Defn}, $params{ApproxOK});
6680 # if Name and Type are missing, assume Name => Type
6681 if (!(exists $params{Name} && exists $params{Type})) {
6682 for my $key (sort keys %params) {
6683 if (s_exists(field_type => $params{$key}) ||
6684 s_exists(geometry_type => $params{$key}))
6686 $params{Name} = $key;
6687 $params{Type} = $params{$key};
6688 delete $params{$key};
6693 my $a = $params{ApproxOK};
6694 delete $params{ApproxOK};
6695 if (exists $params{GeometryType}) {
6696 $params{Type} = $params{GeometryType};
6697 delete $params{GeometryType};
6699 if (s_exists(field_type => $params{Type})) {
6701 _CreateField($self, $fd, $a);
6702 } elsif (s_exists(geometry_type => $params{Type})) {
6704 CreateGeomField($self, $fd, $a);
6705 } elsif ($params{Type} ) {
6706 error(
"Invalid field type: $params{Type}.")
6707 } elsif ($params{Name} ) {
6708 error(
"Missing type for field: $params{Name}.")
6710 error(
"Missing name and type for a field.")
6715 #** @method DataSource()
6720 #** @method Dataset()
6727 #** @method DeleteFeature($fid)
6729 # @param fid feature id
6734 #** @method DeleteField($field)
6736 # Delete an existing field from a layer.
6737 # @param field name (or index) of the field which is deleted
6738 # @note Only non-spatial fields can be deleted.
6741 my ($self, $field) = @_;
6742 my $index = $self->GetLayerDefn->GetFieldIndex($field
6743 _DeleteField($self, $index);
6746 #** @method Erase(Geo::OGR::Layer method, Geo::OGR::Layer result, hashref options, coderef callback, $callback_data)
6748 # The result layer contains features whose geometries represent areas
6749 # that are in the input layer but not in the method layer. The
6750 # features in the result layer have attributes from the input
6751 # layer. The schema of the result layer can be set by the user or, if
6752 # it is empty, is initialized to contain all fields in the input
6754 # @param method method layer.
6755 # @param result result layer.
6756 # @param options a reference to an options hash.
6757 # @param callback [optional] a reference to a subroutine, which will
6758 # be called with parameters (number progress, string msg, callback_data)
6759 # @param callback_data [optional]
6764 #** @method Geo::OGR::Feature Feature($f)
6767 # @param f [optional] feature id, a feature, a row, or a tuple
6769 # @note If the argument feature has a null FID (FID not set) the
6770 # feature is inserted into the layer as a new feature. If the FID is
6771 # non null, then the feature replaces the feature in the layer with
6774 # @return a new Geo::OGR::Feature object that represents the feature
6780 return $self->GetFeature($x) unless $x && ref $x;
6781 # Insert or Set depending on the FID
6783 if (ref $x eq
'ARRAY') {
6784 # FID is the first item in the array
6786 } elsif (ref $x eq
'HASH') {
6793 if (!defined $fid || $fid < 0) {
6794 $self->InsertFeature($x);
6796 $self->SetFeature($x);
6800 #** @method scalar FeatureCount($force = 1)
6802 # A.k.a GetFeatureCount
6809 #** @method Features()
6813 $self->ResetReading;
6815 return $self->GetNextFeature;
6819 #** @method ForFeatures($code, $in_place)
6821 # @note experimental, the syntax may change
6823 # Call code for all features. This is a simple wrapper for
6824 # ResetReading and while(GetNextFeature).
6828 # $layer->ForFeatures(sub {my $f = shift; $self->DeleteFeature($f->FID)}); # empties the layer
6831 # @param code a reference to a subroutine, which is called with each
6832 # feature as an argument
6833 # @param in_place if set to true, the feature is stored back to the
6839 my $in_place = shift;
6840 $self->ResetReading;
6841 while (my $f = $self->GetNextFeature) {
6844 $self->SetFeature($f)
if $in_place;
6848 #** @method ForGeometries($code, $in_place)
6850 # @note experimental, the syntax may change
6852 # Call code for all geometries. This is a simple wrapper for
6853 # ResetReading and while(GetNextFeature).
6858 # $layer->ForGeometries(sub {my $g = shift; $area += $g->Area}); # computes the total area
6861 # @param code a reference to a subroutine, which is called with each
6862 # geometry as an argument
6863 # @param in_place if set to true, the geometry is stored back to the
6869 my $in_place = shift;
6870 $self->ResetReading;
6871 while (my $f = $self->GetNextFeature) {
6872 my $g = $f->Geometry();
6876 $self->SetFeature($f);
6881 #** @method Geometries()
6885 $self->ResetReading;
6887 my $f = $self->GetNextFeature;
6889 return $f->Geometry;
6893 #** @method scalar GeometryType($field)
6895 # @param field the name or index of the spatial field.
6896 # @return the geometry type of the spatial field.
6900 my $d = $self->GetDefn;
6901 my $field = $d->GetGeomFieldIndex(shift
6902 my $fd = $d->_GetGeomFieldDefn($field);
6903 return $fd->Type
if $fd;
6906 #** @method Geo::OGR::DataSource GetDataSource()
6908 # @return the data source object to which this layer object belongs to.
6915 #** @method Geo::OGR::FeatureDefn GetDefn()
6917 # A.k.a GetLayerDefn.
6918 # @return a Geo::OGR::FeatureDefn object.
6922 my $defn = $self->GetLayerDefn;
6926 #** @method list GetExtent($force = 1)
6928 # @param force compute the extent even if it is expensive
6929 # @note In scalar context returns a reference to an anonymous array
6930 # containing the extent.
6931 # @return the extent ($minx, $maxx, $miny, $maxy)
6933 # @return the extent = ($minx, $maxx, $miny, $maxy) as a listref
6938 #** @method scalar GetFIDColumn()
6940 # @return the name of the underlying database column being used as the
6941 # FID column, or "" if not supported.
6946 #** @method Geo::OGR::Feature GetFeature($fid)
6948 # @param fid feature id
6949 # @return a new Geo::OGR::Feature object that represents the feature in the layer.
6952 my ($self, $fid) = @_;
6954 my $f = $self->_GetFeature($fid);
6955 error(2,
"FID=$fid",
'"Feature') unless ref $f eq 'Geo::
OGR::Feature';
6959 #** @method GetFeatureCount()
6961 sub GetFeatureCount {
6964 #** @method scalar GetFeaturesRead()
6968 sub GetFeaturesRead {
6971 #** @method scalar GetFieldDefn($name)
6973 # Get the definition of a field.
6974 # @param name the name of the field.
6975 # @return a Geo::OGR::FieldDefn object.
6979 my $d = $self->GetDefn;
6980 my $field = $d->GetFieldIndex(shift
6981 return $d->_GetFieldDefn($field);
6984 #** @method list GetFieldNames()
6986 # @return a list of the names of the fields in this layer. The
6987 # non-geometry field names are first in the list and then the geometry
6992 my $d = $self->GetDefn;
6994 for (my $i = 0; $i < $d->GetFieldCount; $i++) {
6995 push @ret, $d->GetFieldDefn($i)->Name();
6997 for (my $i = 0; $i < $d->GetGeomFieldCount; $i++) {
6998 push @ret, $d->GetGeomFieldDefn($i)->Name();
7003 #** @method scalar GetGeomFieldDefn($name)
7005 # Get the definition of a spatial field.
7006 # @param name the name of the spatial field.
7007 # @return a Geo::OGR::GeomFieldDefn object.
7009 sub GetGeomFieldDefn {
7011 my $d = $self->GetDefn;
7012 my $field = $d->GetGeomFieldIndex(shift
7013 return $d->_GetGeomFieldDefn($field);
7016 #** @method scalar GetName()
7018 # @return the name of the layer.
7023 #** @method Geo::OGR::Feature GetNextFeature()
7025 # @return iteratively Geo::OGR::Feature objects from the layer. The
7026 # iteration obeys the spatial and the attribute filter.
7028 sub GetNextFeature {
7031 #** @method hash reference GetSchema()
7033 # @brief Get the schema of this layer.
7034 # @note The schema of a layer cannot be set with this method. If you
7035 # have a Geo::OGR::FeatureDefn object before creating the layer, use
7036 # its schema in the Geo::OGR::CreateLayer method.
7037 # @return the schema of this layer, as in Geo::OGR::FeatureDefn::Schema.
7041 carp
"Schema of a layer should not be set directly." if @_;
7042 if (@_ and @_ % 2 == 0) {
7044 if ($schema{Fields}) {
7045 for my $field (@{$schema{Fields}}) {
7046 $self->CreateField($field);
7050 return $self->GetDefn->Schema;
7053 #** @method Geo::OGR::Geometry GetSpatialFilter()
7055 # @return a new Geo::OGR::Geometry object
7057 sub GetSpatialFilter {
7060 #** @method GetStyleTable()
7065 #** @method Identity(Geo::OGR::Layer method, Geo::OGR::Layer result, hashref options, coderef callback, $callback_data)
7067 # The result layer contains features whose geometries represent areas
7068 # that are in the input layer. The features in the result layer have
7069 # attributes from both input and method layers. The schema of the
7070 # result layer can be set by the user or, if it is empty, is
7071 # initialized to contain all fields in input and method layers.
7072 # @param method method layer.
7073 # @param result result layer.
7074 # @param options a reference to an options hash.
7075 # @param callback [optional] a reference to a subroutine, which will
7076 # be called with parameters (number progress, string msg, callback_data)
7077 # @param callback_data [optional]
7082 #** @method InsertFeature($feature)
7084 # Creates a new feature which has the schema of the layer and
7085 # initializes it with data from the argument. Then inserts the feature
7086 # into the layer (using CreateFeature). Uses Geo::OGR::Feature::Row or
7087 # Geo::OGR::Feature::Tuple.
7088 # @param feature a Geo::OGR::Feature object or reference to feature
7089 # data in a hash (as in Geo::OGR::Feature::Row) or in an array (as in
7090 # Geo::OGR::Feature::Tuple)
7091 # @return the new feature.
7095 my $feature = shift;
7096 error(
"Usage: \$feature->InsertFeature(reference to a hash or array).") unless ref($feature);
7097 my $new = Geo::OGR::Feature->new(Schema => $self, Values => $feature);
7098 $self->CreateFeature($new);
7099 return unless defined wantarray;
7103 #** @method Intersection(Geo::OGR::Layer method, Geo::OGR::Layer result, hashref options, coderef callback, $callback_data)
7105 # The result layer contains features whose geometries represent areas
7106 # that are common between features in the input layer and in the
7107 # method layer. The schema of the result layer can be set before
7108 # calling this method, or is initialized to contain all fields from
7109 # this and method layer.
7110 # @param method method layer.
7111 # @param result result layer.
7112 # @param options a reference to an options hash.
7113 # @param callback [optional] a reference to a subroutine, which will
7114 # be called with parameters (number progress, string msg, callback_data)
7115 # @param callback_data [optional]
7120 #** @method ReorderField()
7125 #** @method ReorderFields()
7130 #** @method ResetReading()
7132 # Initialize the layer object for iterative reading.
7137 #** @method RollbackTransaction()
7140 sub RollbackTransaction {
7143 #** @method hash reference Row(%row)
7145 # Get and/or set the data of a feature that has the supplied feature
7146 # id (the next feature obtained with GetNextFeature is used if feature
7147 # id is not given). Calls Geo::OGR::Feature::Row.
7148 # @param row [optional] feature data
7149 # @return a reference to feature data in a hash
7153 my $update = @_ > 0;
7155 my $feature = defined $row{FID} ? $self->GetFeature($row{FID}) : $self->GetNextFeature;
7156 return unless $feature;
7158 if (defined wantarray) {
7159 $ret = $feature->Row(@_);
7163 $self->SetFeature($feature)
if $update;
7164 return unless defined wantarray;
7168 #** @method SetAttributeFilter($filter_string)
7170 # Set or clear the attribute filter.
7171 # @param filter_string a SQL WHERE clause or undef to clear the
7174 sub SetAttributeFilter {
7177 #** @method SetFeature($feature)
7179 # @note The feature should have the same schema as the layer.
7181 # Replaces a feature in the layer based on the given feature's
7182 # id. Requires RandomWrite capability.
7183 # @param feature a Geo::OGR::Feature object
7188 #** @method SetIgnoredFields(@fields)
7190 # @param fields a list of field names
7192 sub SetIgnoredFields {
7195 #** @method SetNextByIndex($new_index)
7197 # @param new_index the index to which set the read cursor in the
7200 sub SetNextByIndex {
7203 #** @method SetSpatialFilter($filter)
7205 # @param filter [optional] a Geo::OGR::Geometry object. If not given,
7206 # removes the filter if there is one.
7208 sub SetSpatialFilter {
7211 #** @method SetSpatialFilterRect($minx, $miny, $maxx, $maxy)
7218 sub SetSpatialFilterRect {
7221 #** @method SetStyleTable()
7226 #** @method Geo::OGR::Geometry SpatialFilter(@filter)
7228 # @param filter [optional] a Geo::OGR::Geometry object or a string. An
7229 # undefined value removes the filter if there is one.
7230 # @return a new Geo::OGR::Geometry object
7231 # @param filter [optional] a rectangle ($minx, $miny, $maxx, $maxy).
7232 # @return a new Geo::OGR::Geometry object
7236 $self->SetSpatialFilter($_[0])
if @_ == 1;
7237 $self->SetSpatialFilterRect(@_)
if @_ == 4;
7238 return unless defined wantarray;
7239 $self->GetSpatialFilter;
7242 #** @method Geo::OSR::SpatialReference SpatialReference($name, Geo::OSR::SpatialReference sr)
7244 # @note A.k.a GetSpatialRef.
7245 # Get or set the projection of a spatial field of this layer. Gets or
7246 # sets the projection of the first field if no field name is given.
7247 # @param name [optional] a name of a spatial field in this layer.
7248 # @param sr [optional] a Geo::OSR::SpatialReference object,
7249 # which replaces the existing projection.
7250 # @return a Geo::OSR::SpatialReference object, which represents the
7251 # projection in the given spatial field.
7253 sub SpatialReference {
7255 my $d = $self->GetDefn;
7256 my $field = @_ == 2 ? $d->GetGeomFieldIndex(shift
7258 my $d2 = $d->_GetGeomFieldDefn($field);
7259 $d2->SpatialReference($sr)
if defined $sr;
7260 return $d2->SpatialReference()
if defined wantarray;
7263 #** @method StartTransaction()
7266 sub StartTransaction {
7269 #** @method SymDifference(Geo::OGR::Layer method, Geo::OGR::Layer result, hashref options, coderef callback, $callback_data)
7271 # The result layer contains features whose geometries represent areas
7272 # that are in either in the input layer or in the method layer but not
7273 # in both. The features in the result layer have attributes from both
7274 # input and method layers. For features which represent areas that are
7275 # only in the input or in the method layer the respective attributes
7276 # have undefined values. The schema of the result layer can be set by
7277 # the user or, if it is empty, is initialized to contain all fields in
7278 # the input and method layers.
7279 # @param method method layer.
7280 # @param result result layer.
7281 # @param options a reference to an options hash.
7282 # @param callback [optional] a reference to a subroutine, which will
7283 # be called with parameters (number progress, string msg, callback_data)
7284 # @param callback_data [optional]
7289 #** @method SyncToDisk()
7295 #** @method scalar TestCapability($cap)
7297 # @param cap A capability string.
7298 # @return a boolean value indicating whether the layer has the
7299 # specified capability.
7301 sub TestCapability {
7302 my($self, $cap) = @_;
7303 return _TestCapability($self, $CAPABILITIES{$cap});
7306 #** @method list Tuple(@tuple)
7308 # Get and/set the data of a feature that has the supplied feature id
7309 # (the next feature obtained with GetNextFeature is used if feature id
7310 # is not given). The expected data in the tuple is: ([feature id,]
7311 # non-spatial fields, spatial fields). Calls Geo::OGR::Feature::Tuple.
7312 # @param tuple [optional] feature data
7313 # @note The schema of the tuple needs to be the same as that of the
7315 # @return a reference to feature data in an array
7320 my $feature = defined $FID ? $self->GetFeature($FID) : $self->GetNextFeature;
7321 return unless $feature;
7323 unshift @_, $feature->GetFID
if $set;
7325 if (defined wantarray) {
7326 @ret = $feature->Tuple(@_);
7328 $feature->Tuple(@_);
7330 $self->SetFeature($feature)
if $set;
7331 return unless defined wantarray;
7335 #** @method Union(Geo::OGR::Layer method, Geo::OGR::Layer result, hashref options, coderef callback, $callback_data)
7337 # The result layer contains features whose geometries represent areas
7338 # that are in either in the input layer or in the method layer. The
7339 # schema of the result layer can be set before calling this method, or
7340 # is initialized to contain all fields from this and method layer.
7341 # @param method method layer.
7342 # @param result result layer.
7343 # @param options a reference to an options hash.
7344 # @param callback [optional] a reference to a subroutine, which will
7345 # be called with parameters (number progress, string msg, callback_data)
7346 # @param callback_data [optional]
7351 #** @method Update(Geo::OGR::Layer method, Geo::OGR::Layer result, hashref options, coderef callback, $callback_data)
7353 # The result layer contains features whose geometries represent areas
7354 # that are either in the input layer or in the method layer. The
7355 # features in the result layer have areas of the features of the
7356 # method layer or those ares of the features of the input layer that
7357 # are not covered by the method layer. The features of the result
7358 # layer get their attributes from the input layer. The schema of the
7359 # result layer can be set by the user or, if it is empty, is
7360 # initialized to contain all fields in the input layer.
7361 # @param method method layer.
7362 # @param result result layer.
7363 # @param options a reference to an options hash.
7364 # @param callback [optional] a reference to a subroutine, which will
7365 # be called with parameters (number progress, string msg, callback_data)
7366 # @param callback_data [optional]
7371 #** @class Geo::OGR::StyleTable
7373 package Geo::OGR::StyleTable;
7377 #** @method AddStyle()
7387 #** @method GetLastStyleName()
7389 sub GetLastStyleName {
7392 #** @method GetNextStyle()
7397 #** @method LoadStyleTable()
7399 sub LoadStyleTable {
7402 #** @method ResetStyleStringReading()
7404 sub ResetStyleStringReading {
7407 #** @method SaveStyleTable()
7409 sub SaveStyleTable {
7416 my $self = Geo::OGRc::new_StyleTable(@_);
7417 bless $self, $pkg
if defined($self);
7421 # @brief Base class for projection related classes.
7426 #** @method list AngularUnits()
7427 # Package subroutine.
7428 # @return list of known angular units.
7431 return keys %ANGULAR_UNITS;
7434 #** @method CreateCoordinateTransformation()
7436 sub CreateCoordinateTransformation {
7439 #** @method list Datums()
7440 # Package subroutine.
7441 # @return list of known datums.
7444 return keys %DATUMS;
7447 #** @method list GetProjectionMethodParamInfo($projection, $parameter)
7448 # Package subroutine.
7449 # @param projection one of Geo::OSR::Projections
7450 # @param parameter one of Geo::OSR::Parameters
7451 # @return a list ($user_friendly_name, $type, $default_value).
7453 sub GetProjectionMethodParamInfo {
7456 #** @method list GetProjectionMethodParameterList($projection)
7457 # Package subroutine.
7458 # @param projection one of Geo::OSR::Projections
7459 # @return a list (arrayref parameters, $projection_name).
7461 sub GetProjectionMethodParameterList {
7464 #** @method array reference GetProjectionMethods()
7465 # Package subroutine.
7466 # @deprecated Use Geo::OSR::Projections.
7468 # @return reference to an array of possible projection methods.
7470 sub GetProjectionMethods {
7473 #** @method scalar GetUserInputAsWKT($name)
7474 # Package subroutine.
7475 # @param name the user input
7476 # @return a WKT string.
7478 sub GetUserInputAsWKT {
7481 #** @method scalar GetWellKnownGeogCSAsWKT($name)
7482 # Package subroutine.
7483 # @brief Get well known geographic coordinate system as WKT
7484 # @param name a well known name
7485 # @return a WKT string.
7487 sub GetWellKnownGeogCSAsWKT {
7490 #** @method list LinearUnits()
7491 # Package subroutine.
7492 # @return list of known linear units.
7495 return keys %LINEAR_UNITS;
7498 #** @method OAO_Down()
7503 #** @method OAO_East()
7508 #** @method OAO_North()
7513 #** @method OAO_Other()
7518 #** @method OAO_South()
7523 #** @method OAO_Up()
7528 #** @method OAO_West()
7533 #** @method list Parameters()
7534 # Package subroutine.
7535 # @return list of known projection parameters.
7538 return keys %PARAMETERS;
7541 #** @method list Projections()
7542 # Package subroutine.
7543 # @return list of known projections.
7546 return keys %PROJECTIONS;
7549 #** @method SRS_PM_GREENWICH()
7551 sub SRS_PM_GREENWICH {
7554 #** @method SRS_WGS84_INVFLATTENING()
7556 sub SRS_WGS84_INVFLATTENING {
7559 #** @method SRS_WGS84_SEMIMAJOR()
7561 sub SRS_WGS84_SEMIMAJOR {
7564 #** @method SRS_WKT_WGS84()
7569 #** @class Geo::OSR::CoordinateTransformation
7570 # @brief An object for transforming from one projection to another.
7573 package Geo::OSR::CoordinateTransformation;
7577 #** @method array reference TransformPoint($x, $y, $z)
7581 # @param z [optional]
7582 # @return arrayref = [$x, $y, $z]
7584 sub TransformPoint {
7587 #** @method TransformPoints(arrayref points)
7589 # @param points [in/out] a reference to a list of points (line string
7590 # or ring) that is modified in-place. A list of points is: ([x, y, z],
7591 # [x, y, z], ...), where z is optional. Supports also lists of line
7592 # strings and polygons.
7594 sub TransformPoints {
7595 my($self, $points) = @_;
7596 _TransformPoints($self, $points),
return unless ref($points->[0]->[0]);
7597 for my $p (@$points) {
7598 TransformPoints($self, $p);
7602 # This file was automatically generated by SWIG (http://www.swig.org).
7605 # Do not make changes to this file unless you know what you are doing--modify
7606 # the SWIG interface file instead.
7609 #** @method Geo::OSR::CoordinateTransformation new($src, $dst)
7611 # @param src a Geo::OSR::SpatialReference object
7612 # @param dst a Geo::OSR::SpatialReference object
7613 # @return a new Geo::OSR::CoordinateTransformation object
7617 my $self = Geo::OSRc::new_CoordinateTransformation(@_);
7618 bless $self, $pkg
if defined($self);
7621 #** @class Geo::OSR::SpatialReference
7622 # @brief A spatial reference system.
7623 # @details <a href="http://www.gdal.org/classOGRSpatialReference.html">Documentation
7624 # of the underlying C++ class at www.gdal.org</a>
7626 package Geo::OSR::SpatialReference;
7635 #** @method AutoIdentifyEPSG()
7637 # Set EPSG authority info if possible.
7639 sub AutoIdentifyEPSG {
7642 #** @method Geo::OSR::SpatialReference Clone()
7644 # Make a duplicate of this SpatialReference object.
7645 # @return a new Geo::OSR::SpatialReference object
7650 #** @method Geo::OSR::SpatialReference CloneGeogCS()
7652 # Make a duplicate of the GEOGCS node of this SpatialReference object.
7653 # @return a new Geo::OSR::SpatialReference object
7658 #** @method ConvertToOtherProjection()
7660 sub ConvertToOtherProjection {
7663 #** @method CopyGeogCSFrom($rhs)
7665 # @param rhs Geo::OSR::SpatialReference
7667 sub CopyGeogCSFrom {
7670 #** @method EPSGTreatsAsLatLong()
7672 # Returns TRUE if EPSG feels this geographic coordinate system should be treated as having lat/long coordinate ordering.
7674 sub EPSGTreatsAsLatLong {
7677 #** @method EPSGTreatsAsNorthingEasting()
7679 sub EPSGTreatsAsNorthingEasting {
7682 #** @method Export($format)
7684 # Export the spatial reference to a selected format.
7687 # @param format One of the following. The return value is explained
7688 # after the format. Other arguments are explained in parenthesis.
7689 # - WKT (Text): Well Known Text string
7690 # - PrettyWKT: Well Known Text string nicely formatted (simplify)
7691 # - Proj4: PROJ.4 string
7692 # - PCI: a list: ($proj_string, $units, [$parms1, ...])
7693 # - USGS: a list: ($code, $zone, [$parms1, ...], $datum)
7694 # - GML (XML): GML based string (dialect)
7695 # - MapInfoCS (MICoordSys): MapInfo style co-ordinate system definition
7697 # @note The named parameter syntax also works and is needed is those
7698 # cases when other arguments need or may be given. The format should
7699 # be given using key as, 'to' or 'format'.
7701 # @note ExportTo* and AsText methods also exist but are not documented here.
7703 # @return a scalar or a list depending on the export format
7708 $format = pop
if @_ == 1;
7711 my $simplify = $params{simplify}
7712 my $dialect = $params{dialect}
7714 WKT => sub {
return ExportToWkt($self) },
7715 Text => sub {
return ExportToWkt($self) },
7716 PrettyWKT => sub {
return ExportToPrettyWkt($self, $simplify) },
7717 Proj4 => sub {
return ExportToProj4($self) },
7718 PCI => sub {
return ExportToPCI($self) },
7719 USGS => sub {
return ExportToUSGS($self) },
7720 GML => sub {
return ExportToXML($self, $dialect) },
7721 XML => sub {
return ExportToXML($self, $dialect) },
7722 MICoordSys => sub {
return ExportToMICoordSys() },
7723 MapInfoCS => sub {
return ExportToMICoordSys() },
7725 error(1, $format, \%converters) unless $converters{$format};
7726 return $converters{$format}->();
7735 #** @method FixupOrdering()
7741 #** @method scalar GetAngularUnits()
7745 sub GetAngularUnits {
7748 #** @method GetAngularUnitsName()
7750 sub GetAngularUnitsName {
7753 #** @method scalar GetAttrValue($name, $child = 0)
7762 #** @method scalar GetAuthorityCode($target_key)
7767 sub GetAuthorityCode {
7770 #** @method scalar GetAuthorityName($target_key)
7775 sub GetAuthorityName {
7778 #** @method GetAxisName()
7783 #** @method GetAxisOrientation()
7785 sub GetAxisOrientation {
7788 #** @method GetInvFlattening()
7791 sub GetInvFlattening {
7794 #** @method scalar GetLinearUnits()
7798 sub GetLinearUnits {
7801 #** @method scalar GetLinearUnitsName()
7805 sub GetLinearUnitsName {
7808 #** @method scalar GetNormProjParm($name, $default_val = 0.0)
7811 # @param default_val
7814 sub GetNormProjParm {
7817 #** @method scalar GetProjParm($name, $default_val = 0.0)
7820 # @param default_val
7826 #** @method GetSemiMajor()
7832 #** @method GetSemiMinor()
7838 #** @method GetTOWGS84()
7840 # @return array = ($p1, $p2, $p3, $p4, $p5, $p6, $p7)
7845 #** @method GetTargetLinearUnits()
7847 sub GetTargetLinearUnits {
7850 #** @method GetUTMZone()
7852 # Get UTM zone information.
7853 # @return The UTM zone (integer). In scalar context the returned value
7854 # is negative for southern hemisphere zones. In list context returns
7855 # two values ($zone, $north), where $zone is always non-negative and
7856 # $north is true or false.
7860 my $zone = _GetUTMZone($self);
7867 return ($zone, $north);
7873 #** @method ImportFromOzi()
7878 #** @method scalar IsCompound()
7885 #** @method scalar IsGeocentric()
7892 #** @method scalar IsGeographic()
7899 #** @method scalar IsLocal()
7906 #** @method scalar IsProjected()
7913 #** @method scalar IsSame($rs)
7915 # @param rs a Geo::OSR::SpatialReference object
7921 #** @method scalar IsSameGeogCS($rs)
7923 # @param rs a Geo::OSR::SpatialReference object
7929 #** @method scalar IsSameVertCS($rs)
7931 # @param rs a Geo::OSR::SpatialReference object
7937 #** @method scalar IsVertical()
7944 #** @method MorphFromESRI()
7950 #** @method MorphToESRI()
7956 #** @method Set(%params)
7958 # Set a parameter or parameters in the spatial reference object.
7959 # @param params Named parameters. Recognized keys and respective
7960 # values are the following.
7961 # - Authority: authority name (give also TargetKey, Node and Code)
7963 # - Node: partial or complete path to the target node (Node and Value together sets an attribute value)
7964 # - Code: code for value with an authority
7965 # - Value: value to be assigned to a node, a projection parameter or an object
7966 # - AngularUnits: angular units for the geographic coordinate system (give also Value) (one of Geo::OSR::LinearUnits)
7967 # - LinearUnits: linear units for the target node or the object (give also Value and optionally Node) (one of Geo::OSR::LinearUnits)
7968 # - Parameter: projection parameter to set (give also Value and Normalized) (one of Geo::OSR::Parameters)
7969 # - Normalized: set to true to indicate that the Value argument is in "normalized" form
7970 # - Name: a well known name of a geographic coordinate system (e.g. WGS84)
7971 # - GuessFrom: arbitrary text that specifies a projection ("user input")
7972 # - LOCAL_CS: name of a local coordinate system
7973 # - GeocentricCS: name of a geocentric coordinate system
7974 # - VerticalCS: name of a vertical coordinate system (give also Datum and optionally VertDatumType [default is 2005])
7975 # - Datum: a known (OGC or EPSG) name (or(?) one of Geo::OSR::Datums)
7976 # - CoordinateSystem: 'WGS', 'UTM', 'State Plane', or a user visible name (give optionally also Parameters, Zone, North, NAD83, UnitName, UnitConversionFactor, Datum, Spheroid, HorizontalCS, and/or VerticalCS
7977 # - Parameters: a reference to a list containing the coordinate system or projection parameters
7978 # - Zone: zone for setting up UTM or State Plane coordinate systems (State Plane zone in USGS numbering scheme)
7979 # - North: set false for southern hemisphere
7980 # - NAD83: set false if the NAD27 zone definition should be used instead of NAD83
7981 # - UnitName: to override the legal definition for a zone
7982 # - UnitConversionFactor: to override the legal definition for a zone
7983 # - Spheroid: user visible name
7984 # - HorizontalCS: Horizontal coordinate system name
7985 # - Projection: name of a projection, one of Geo::OSR::Projections (give also optionally Parameters and Variant)
7987 # @note Numerous Set* methods also exist but are not documented here.
7990 my($self, %params) = @_;
7991 if (exists $params{Authority} and exists $params{TargetKey} and exists $params{Node} and exists $params{Code}) {
7992 SetAuthority($self, $params{TargetKey}, $params{Authority}, $params{Code});
7993 } elsif (exists $params{Node} and exists $params{Value}) {
7994 SetAttrValue($self, $params{Node}, $params{Value});
7995 } elsif (exists $params{AngularUnits} and exists $params{Value}) {
7996 SetAngularUnits($self, $params{AngularUnits}, $params{Value});
7997 } elsif (exists $params{LinearUnits} and exists $params{Node} and exists $params{Value}) {
7998 SetTargetLinearUnits($self, $params{Node}, $params{LinearUnits}, $params{Value});
7999 } elsif (exists $params{LinearUnits} and exists $params{Value}) {
8000 SetLinearUnitsAndUpdateParameters($self, $params{LinearUnits}, $params{Value});
8001 } elsif ($params{Parameter} and exists $params{Value}) {
8002 error(1, $params{Parameter}, \%Geo::OSR::PARAMETERS) unless exists $Geo::OSR::PARAMETERS{$params{Parameter}};
8003 $params{Normalized} ?
8004 SetNormProjParm($self, $params{Parameter}, $params{Value}) :
8005 SetProjParm($self, $params{Parameter}, $params{Value});
8006 } elsif (exists $params{Name}) {
8007 SetWellKnownGeogCS($self, $params{Name});
8008 } elsif (exists $params{GuessFrom}) {
8009 SetFromUserInput($self, $params{GuessFrom});
8010 } elsif (exists $params{LOCAL_CS}) {
8011 SetLocalCS($self, $params{LOCAL_CS});
8012 } elsif (exists $params{GeocentricCS}) {
8013 SetGeocCS($self, $params{GeocentricCS});
8014 } elsif (exists $params{VerticalCS} and $params{Datum}) {
8015 my $type = $params{VertDatumType} || 2005;
8016 SetVertCS($self, $params{VerticalCS}, $params{Datum}, $type);
8017 } elsif (exists $params{CoordinateSystem}) {
8018 my @parameters = ();
8019 @parameters = @{$params{Parameters}}
if ref($params{Parameters});
8020 if ($params{CoordinateSystem} eq
'State Plane' and exists $params{Zone}) {
8021 my $NAD83 = exists $params{NAD83} ? $params{NAD83} : 1;
8022 my $name = exists $params{UnitName} ? $params{UnitName} : undef;
8023 my $c = exists $params{UnitConversionFactor} ? $params{UnitConversionFactor} : 0.0;
8024 SetStatePlane($self, $params{Zone}, $NAD83, $name, $c);
8025 } elsif ($params{CoordinateSystem} eq
'UTM' and exists $params{Zone} and exists $params{North}) {
8026 my $north = exists $params{North} ? $params{North} : 1;
8027 SetUTM($self, $params{Zone}, $north);
8028 } elsif ($params{CoordinateSystem} eq
'WGS') {
8029 SetTOWGS84($self, @parameters);
8030 } elsif ($params{CoordinateSystem} and $params{Datum} and $params{Spheroid}) {
8031 SetGeogCS($self, $params{CoordinateSystem}, $params{Datum}, $params{Spheroid}, @parameters);
8032 } elsif ($params{CoordinateSystem} and $params{HorizontalCS} and $params{VerticalCS}) {
8033 SetCompoundCS($self, $params{CoordinateSystem}, $params{HorizontalCS}, $params{VerticalCS});
8035 SetProjCS($self, $params{CoordinateSystem});
8037 } elsif (exists $params{Projection}) {
8038 error(1, $params{Projection}, \%Geo::OSR::PROJECTIONS) unless exists $Geo::OSR::PROJECTIONS{$params{Projection}};
8039 my @parameters = ();
8040 @parameters = @{$params{Parameters}}
if ref($params{Parameters});
8041 if ($params{Projection} eq
'Albers_Conic_Equal_Area') {
8042 SetACEA($self, @parameters);
8043 } elsif ($params{Projection} eq
'Azimuthal_Equidistant') {
8044 SetAE($self, @parameters);
8045 } elsif ($params{Projection} eq
'Bonne') {
8046 SetBonne($self, @parameters);
8047 } elsif ($params{Projection} eq
'Cylindrical_Equal_Area') {
8048 SetCEA($self, @parameters);
8049 } elsif ($params{Projection} eq
'Cassini_Soldner') {
8050 SetCS($self, @parameters);
8051 } elsif ($params{Projection} eq
'Equidistant_Conic') {
8052 SetEC($self, @parameters);
8053 # Eckert_I, Eckert_II, Eckert_III, Eckert_V ?
8054 } elsif ($params{Projection} eq
'Eckert_IV') {
8055 SetEckertIV($self, @parameters);
8056 } elsif ($params{Projection} eq
'Eckert_VI') {
8057 SetEckertVI($self, @parameters);
8058 } elsif ($params{Projection} eq
'Equirectangular') {
8060 SetEquirectangular($self, @parameters) :
8061 SetEquirectangular2($self, @parameters);
8062 } elsif ($params{Projection} eq
'Gauss_Schreiber_Transverse_Mercator') {
8063 SetGaussSchreiberTMercator($self, @parameters);
8064 } elsif ($params{Projection} eq
'Gall_Stereographic') {
8065 SetGS($self, @parameters);
8066 } elsif ($params{Projection} eq
'Goode_Homolosine') {
8067 SetGH($self, @parameters);
8068 } elsif ($params{Projection} eq
'Interrupted_Goode_Homolosine') {
8070 } elsif ($params{Projection} eq
'Geostationary_Satellite') {
8071 SetGEOS($self, @parameters);
8072 } elsif ($params{Projection} eq
'Gnomonic') {
8073 SetGnomonic($self, @parameters);
8074 } elsif ($params{Projection} eq
'Hotine_Oblique_Mercator') {
8075 # Hotine_Oblique_Mercator_Azimuth_Center ?
8076 SetHOM($self, @parameters);
8077 } elsif ($params{Projection} eq
'Hotine_Oblique_Mercator_Two_Point_Natural_Origin') {
8078 SetHOM2PNO($self, @parameters);
8079 } elsif ($params{Projection} eq
'Krovak') {
8080 SetKrovak($self, @parameters);
8081 } elsif ($params{Projection} eq
'Lambert_Azimuthal_Equal_Area') {
8082 SetLAEA($self, @parameters);
8083 } elsif ($params{Projection} eq
'Lambert_Conformal_Conic_2SP') {
8084 SetLCC($self, @parameters);
8085 } elsif ($params{Projection} eq
'Lambert_Conformal_Conic_1SP') {
8086 SetLCC1SP($self, @parameters);
8087 } elsif ($params{Projection} eq
'Lambert_Conformal_Conic_2SP_Belgium') {
8088 SetLCCB($self, @parameters);
8089 } elsif ($params{Projection} eq
'miller_cylindrical') {
8090 SetMC($self, @parameters);
8091 } elsif ($params{Projection} =~ /^Mercator/) {
8092 # Mercator_1SP, Mercator_2SP, Mercator_Auxiliary_Sphere ?
8093 # variant is in Variant (or Name)
8094 SetMercator($self, @parameters);
8095 } elsif ($params{Projection} eq
'Mollweide') {
8096 SetMollweide($self, @parameters);
8097 } elsif ($params{Projection} eq
'New_Zealand_Map_Grid') {
8098 SetNZMG($self, @parameters);
8099 } elsif ($params{Projection} eq
'Oblique_Stereographic') {
8100 SetOS($self, @parameters);
8101 } elsif ($params{Projection} eq
'Orthographic') {
8102 SetOrthographic($self, @parameters);
8103 } elsif ($params{Projection} eq
'Polyconic') {
8104 SetPolyconic($self, @parameters);
8105 } elsif ($params{Projection} eq
'Polar_Stereographic') {
8106 SetPS($self, @parameters);
8107 } elsif ($params{Projection} eq
'Robinson') {
8108 SetRobinson($self, @parameters);
8109 } elsif ($params{Projection} eq
'Sinusoidal') {
8110 SetSinusoidal($self, @parameters);
8111 } elsif ($params{Projection} eq
'Stereographic') {
8112 SetStereographic($self, @parameters);
8113 } elsif ($params{Projection} eq
'Swiss_Oblique_Cylindrical') {
8114 SetSOC($self, @parameters);
8115 } elsif ($params{Projection} eq
'Transverse_Mercator_South_Orientated') {
8116 SetTMSO($self, @parameters);
8117 } elsif ($params{Projection} =~ /^Transverse_Mercator/) {
8118 my($variant) = $params{Projection} =~ /^Transverse_Mercator_(\w+)/;
8121 SetTMVariant($self, $variant, @parameters) :
8122 SetTM($self, @parameters);
8123 } elsif ($params{Projection} eq
'Tunisia_Mining_Grid') {
8124 SetTMG($self, @parameters);
8125 } elsif ($params{Projection} eq
'VanDerGrinten') {
8126 SetVDG($self, @parameters);
8128 # Aitoff, Craster_Parabolic, International_Map_of_the_World_Polyconic, Laborde_Oblique_Mercator
8129 # Loximuthal, Miller_Cylindrical, Quadrilateralized_Spherical_Cube, Quartic_Authalic, Two_Point_Equidistant
8130 # Wagner_I, Wagner_II, Wagner_III, Wagner_IV, Wagner_V, Wagner_VI, Wagner_VII
8131 # Winkel_I, Winkel_II, Winkel_Tripel
8133 SetProjection($self, $params{Projection});
8136 error(
"Not enough information to create a spatial reference object.");
8140 #** @method SetMercator2SP()
8142 sub SetMercator2SP {
8145 #** @method StripCTParms()
8151 #** @method Validate()
8157 #** @method Geo::OSR::SpatialReference new(%params)
8159 # Create a new spatial reference object using a named parameter. This
8160 # constructor recognizes the following key words (alternative in
8161 # parenthesis): WKT (Text), Proj4, ESRI, EPSG, EPSGA, PCI, USGS, GML
8162 # (XML), URL, ERMapper (ERM), MapInfoCS (MICoordSys). The value
8163 # depends on the key.
8164 # - WKT: Well Known Text string
8165 # - Proj4: PROJ.4 string
8166 # - ESRI: reference to a list of strings (contents of ESRI .prj file)
8167 # - EPSG: EPSG code number
8168 # - EPSGA: EPSG code number (the resulting CS will have EPSG preferred axis ordering)
8169 # - PCI: listref: [PCI_projection_string, Grid_units_code, [17 cs parameters]]
8170 # - USGS: listref: [Projection_system_code, Zone, [15 cs parameters], Datum_code, Format_flag]
8172 # - URL: URL for downloading the spatial reference from
8173 # - ERMapper: listref: [Projection, Datum, Units]
8174 # - MapInfoCS: MapInfo style co-ordinate system definition
8176 # For more information, consult the import methods in <a href="http://www.gdal.org/classOGRSpatialReference.html">OGR documentation</a>.
8178 # @note ImportFrom* methods also exist but are not documented here.
8182 # $sr = Geo::OSR::SpatialReference->new( key => value );
8184 # @return a new Geo::OSR::SpatialReference object
8189 my $self = Geo::OSRc::new_SpatialReference();
8190 if (exists $param{WKT}) {
8191 ImportFromWkt($self, $param{WKT});
8192 } elsif (exists $param{Text}) {
8193 ImportFromWkt($self, $param{Text});
8194 } elsif (exists $param{Proj4}) {
8195 ImportFromProj4($self, $param{Proj4});
8196 } elsif (exists $param{ESRI}) {
8197 ImportFromESRI($self, @{$param{ESRI}});
8198 } elsif (exists $param{EPSG}) {
8199 ImportFromEPSG($self, $param{EPSG});
8200 } elsif (exists $param{EPSGA}) {
8201 ImportFromEPSGA($self, $param{EPSGA});
8202 } elsif (exists $param{PCI}) {
8203 ImportFromPCI($self, @{$param{PCI}});
8204 } elsif (exists $param{USGS}) {
8205 ImportFromUSGS($self, @{$param{USGS}});
8206 } elsif (exists $param{XML}) {
8207 ImportFromXML($self, $param{XML});
8208 } elsif (exists $param{GML}) {
8209 ImportFromGML($self, $param{GML});
8210 } elsif (exists $param{URL}) {
8211 ImportFromUrl($self, $param{URL});
8212 } elsif (exists $param{ERMapper}) {
8213 ImportFromERM($self, @{$param{ERMapper}});
8214 } elsif (exists $param{ERM}) {
8215 ImportFromERM($self, @{$param{ERM}});
8216 } elsif (exists $param{MICoordSys}) {
8217 ImportFromMICoordSys($self, $param{MICoordSys});
8218 } elsif (exists $param{MapInfoCS}) {
8219 ImportFromMICoordSys($self, $param{MapInfoCS});
8220 } elsif (exists $param{WGS}) {
8222 SetWellKnownGeogCS($self,
'WGS'.$param{WGS});
8224 confess last_error() if $@;
8226 error(
"Unrecognized/missing parameters: @_.");
8228 bless $self, $pkg
if defined $self;