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 CreatePansharpenedVRT()
67 sub CreatePansharpenedVRT {
70 #** @method scalar DataTypeIsComplex($DataType)
72 # @param DataType A GDAL raster cell data type (one of those listed by Geo::GDAL::DataTypes).
73 # @return true if the data type is a complex number.
75 sub DataTypeIsComplex {
76 return _DataTypeIsComplex(s2i(data_type => shift));
79 #** @method list DataTypeValueRange($DataType)
81 # @param DataType Data type (one of those listed by Geo::GDAL::DataTypes).
82 # @note Some returned values are inaccurate.
84 # @return the minimum, maximum range of the data type.
86 sub DataTypeValueRange {
89 # these values are from gdalrasterband.cpp
90 return (0,255) if $t =~ /Byte/;
91 return (0,65535) if $t =~/UInt16/;
92 return (-32768,32767) if $t =~/Int16/;
93 return (0,4294967295) if $t =~/UInt32/;
94 return (-2147483648,2147483647) if $t =~/Int32/;
95 return (-4294967295.0,4294967295.0) if $t =~/Float32/;
96 return (-4294967295.0,4294967295.0) if $t =~/Float64/;
99 #** @method list DataTypes()
100 # Package subroutine.
101 # @return a list of GDAL raster cell data types. These are currently:
102 # Byte, CFloat32, CFloat64, CInt16, CInt32, Float32, Float64, Int16, Int32, UInt16, UInt32, and Unknown.
108 #** @method scalar DecToDMS($angle, $axis, $precision=2)
109 # Package subroutine.
110 # Convert decimal degrees to degrees, minutes, and seconds string
111 # @param angle A number
112 # @param axis A string specifying latitude or longitude ('Long').
114 # @return a string nndnn'nn.nn'"L where n is a number and L is either
120 #** @method scalar DecToPackedDMS($dec)
121 # Package subroutine.
122 # @param dec Decimal degrees
123 # @return packed DMS, i.e., a number DDDMMMSSS.SS
128 #** @method DontUseExceptions()
129 # Package subroutine.
130 # Do not use the Perl exception mechanism for GDAL messages. Instead
131 # the messages are printed to standard error.
133 sub DontUseExceptions {
136 #** @method Geo::GDAL::Driver Driver($Name)
137 # Package subroutine.
138 # Access a format driver.
139 # @param Name The short name of the driver. One of
140 # Geo::GDAL::DriverNames or Geo::OGR::DriverNames.
141 # @note This subroutine is imported into the main namespace if Geo::GDAL
142 # is used with qw/:all/.
143 # @return a Geo::GDAL::Driver object.
146 return 'Geo::GDAL::Driver' unless @_;
148 my $driver = GetDriver($name);
149 error("Driver \"$name\" not found. Is it built in? Check with Geo::GDAL::Drivers or Geo::OGR::Drivers.")
154 #** @method list DriverNames()
155 # Package subroutine.
156 # Available raster format drivers.
158 # perl -MGeo::GDAL -e '@d=Geo::GDAL::DriverNames;print "@d\n"'
160 # @note Use Geo::OGR::DriverNames for vector drivers.
161 # @return a list of the short names of all available GDAL raster drivers.
166 #** @method list Drivers()
167 # Package subroutine.
168 # @note Use Geo::OGR::Drivers for vector drivers.
169 # @return a list of all available GDAL raster drivers.
173 for my $i (0..GetDriverCount()-1) {
174 my $driver = GetDriver($i);
175 push @drivers, $driver if $driver->TestCapability('RASTER');
180 #** @method EscapeString()
185 #** @method scalar FindFile($basename)
186 # Package subroutine.
187 # Search for GDAL support files.
192 # $a = Geo::GDAL::FindFile('pcs.csv');
193 # print STDERR "$a\n";
195 # Prints (for example):
197 # c:\msys\1.0\local\share\gdal\pcs.csv
200 # @param basename The name of the file to search for. For example
202 # @return the path to the searched file or undef.
212 #** @method FinderClean()
213 # Package subroutine.
214 # Clear the set of support file search paths.
219 #** @method GOA2GetAccessToken()
221 sub GOA2GetAccessToken {
224 #** @method GOA2GetAuthorizationURL()
226 sub GOA2GetAuthorizationURL {
229 #** @method GOA2GetRefreshToken()
231 sub GOA2GetRefreshToken {
234 #** @method GetActualURL()
239 #** @method scalar GetCacheMax()
240 # Package subroutine.
241 # @return maximum amount of memory (as bytes) for caching within GDAL.
246 #** @method scalar GetCacheUsed()
247 # Package subroutine.
248 # @return the amount of memory currently used for caching within GDAL.
253 #** @method scalar GetConfigOption($key)
254 # Package subroutine.
255 # @param key A GDAL config option. Consult <a
256 # href="https://trac.osgeo.org/gdal/wiki/ConfigOptions">the GDAL
257 # documentation</a> for available options and their use.
258 # @return the value of the GDAL config option.
260 sub GetConfigOption {
263 #** @method scalar GetDataTypeSize($DataType)
264 # Package subroutine.
265 # @param DataType A GDAL raster cell data type (one of those listed by Geo::GDAL::DataTypes).
266 # @return the size as the number of bits.
268 sub GetDataTypeSize {
269 return _GetDataTypeSize(s2i(data_type => shift, 1));
272 #** @method GetErrorCounter()
274 sub GetErrorCounter {
277 #** @method GetFileSystemOptions()
279 sub GetFileSystemOptions {
282 #** @method GetFileSystemsPrefixes()
284 sub GetFileSystemsPrefixes {
287 #** @method GetJPEG2000StructureAsString()
289 sub GetJPEG2000StructureAsString {
292 #** @method GetSignedURL()
297 #** @method Geo::GDAL::Driver IdentifyDriver($path, $siblings)
298 # Package subroutine.
299 # @param path a dataset path.
300 # @param siblings [optional] A list of names of files that belong to the data format.
301 # @return a Geo::GDAL::Driver.
306 #** @method IdentifyDriverEx()
308 sub IdentifyDriverEx {
311 #** @method MkdirRecursive()
316 #** @method Geo::GDAL::Dataset Open(%params)
317 # Package subroutine.
319 # An example, which opens an existing raster dataset for editing:
321 # use Geo::GDAL qw/:all/;
322 # $ds = Open(Name => 'existing.tiff', Access => 'Update');
324 # @param params Named parameters:
325 # - \a Name Dataset string (typically a filename). Default is '.'.
326 # - \a Access Access type, either 'ReadOnly' or 'Update'. Default is 'ReadOnly'.
327 # - \a Type Dataset type, either 'Raster', 'Vector', or 'Any'. Default is 'Any'.
328 # - \a Options A hash of GDAL open options passed to candidate drivers. Default is {}.
329 # - \a Files A list of names of files that are auxiliary to the main file. Default is [].
331 # @note This subroutine is imported into the main namespace if Geo::GDAL
332 # is use'd with qw/:all/.
334 # @note Some datasets / dataset strings do not explicitly imply the
335 # dataset type (for example a PostGIS database). If the type is not
336 # specified in such a case the returned dataset may be of either type.
338 # @return a new Geo::GDAL::Dataset object if success.
341 my $p = named_parameters(\@_, Name => '.', Access => 'ReadOnly', Type => 'Any', Options => {}, Files => []);
343 my %o = (READONLY => 1, UPDATE => 1);
344 error(1, $p->{access}, \%o) unless $o{uc($p->{access})};
345 push @flags, uc($p->{access});
346 %o = (RASTER => 1, VECTOR => 1, ANY => 1);
347 error(1, $p->{type}, \%o) unless $o{uc($p->{type})};
348 push @flags, uc($p->{type}) unless uc($p->{type}) eq 'ANY';
349 my $dataset = OpenEx(Name => $p->{name}, Flags => \@flags, Options => $p->{options}, Files => $p->{files});
351 my $t = "Failed to open $p->{name}.";
352 $t .= " Is it a ".lc($p->{type})." dataset?" unless uc($p->{type}) eq 'ANY';
358 #** @method Geo::GDAL::Dataset OpenEx(%params)
359 # Package subroutine.
360 # The generic dataset open method, used internally by all Open and OpenShared methods.
361 # @param params Named parameters:
362 # - \a Name The name of the data set or source to open. (Default is '.')
363 # - \a Flags A list of access mode flags. Available flags are listed by Geo::GDAL::OpenFlags(). (Default is [])
364 # - \a Drivers A list of short names of drivers that may be used. Empty list means all. (Default is [])
365 # - \a Options A hash of GDAL open options passed to candidate drivers. (Default is {})
366 # - \a Files A list of names of files that are auxiliary to the main file. (Default is [])
370 # $ds = Geo::GDAL::OpenEx(Name => 'existing.tiff', Flags => [qw/RASTER UPDATE/]);
372 # @return a new Geo::GDAL::Dataset object.
375 my $p = named_parameters(\@_, Name => '.', Flags => [], Drivers => [], Options => {}, Files => []);
377 my $name = shift // '';
379 $p = {name => $name, flags => \@flags, drivers => [], options => {}, files => []};
383 for my $flag (@{$p->{flags}}) {
384 $f |= s2i(open_flag => $flag);
388 return _OpenEx($p->{name}, $p->{flags}, $p->{drivers}, $p->{options}, $p->{files});
391 #** @method list OpenFlags()
392 # Package subroutine.
393 # @return a list of GDAL data set open modes. These are currently:
394 # ALL, GNM, RASTER, READONLY, SHARED, UPDATE, VECTOR, and VERBOSE_ERROR.
400 #** @method scalar PackCharacter($DataType)
401 # Package subroutine.
402 # Get the character that is needed for Perl's pack and unpack when
403 # they are used with Geo::GDAL::Band::ReadRaster and
404 # Geo::GDAL::Band::WriteRaster. Note that Geo::GDAL::Band::ReadTile
405 # and Geo::GDAL::Band::WriteTile have simpler interfaces that do not
406 # require pack and unpack.
407 # @param DataType A GDAL raster cell data type, typically from $band->DataType.
408 # @return a character which can be used in Perl's pack and unpack.
412 $t = i2s(data_type => $t);
413 s2i(data_type => $t); # test
414 my $is_big_endian = unpack("h*", pack("s", 1)) =~ /01/; # from Programming Perl
415 return 'C' if $t =~ /^Byte$/;
416 return ($is_big_endian ? 'n': 'v') if $t =~ /^UInt16$/;
417 return 's' if $t =~ /^Int16$/;
418 return ($is_big_endian ? 'N' : 'V') if $t =~ /^UInt32$/;
419 return 'l' if $t =~ /^Int32$/;
420 return 'f' if $t =~ /^Float32$/;
421 return 'd' if $t =~ /^Float64$/;
424 #** @method scalar PackedDMSToDec($packed)
425 # Package subroutine.
426 # @param packed DMS as a number DDDMMMSSS.SS
427 # @return decimal degrees
432 #** @method PopFinderLocation()
433 # Package subroutine.
434 # Remove the latest addition from the set of support file search
435 # paths. Note that calling this subroutine may remove paths GDAL put
438 sub PopFinderLocation {
441 #** @method PushFinderLocation($path)
442 # Package subroutine.
443 # Add a path to the set of paths from where GDAL support files are
444 # sought. Note that GDAL puts initially into the finder the current
445 # directory and value of GDAL_DATA environment variable (if it
446 # exists), installation directory (prepended with '/share/gdal' or
447 # '/Resources/gdal'), or '/usr/local/share/gdal'. It is usually only
448 # needed to add paths to the finder if using an alternate set of data
449 # files or a non-installed GDAL is used (as in testing).
451 sub PushFinderLocation {
454 #** @method list RIOResamplingTypes()
455 # Package subroutine.
456 # @return a list of GDAL raster IO resampling methods. These are currently:
457 # Average, Bilinear, Cubic, CubicSpline, Gauss, Lanczos, Mode, and NearestNeighbour.
459 sub RIOResamplingTypes {
460 return @RIO_RESAMPLING_TYPES;
463 #** @method list ResamplingTypes()
464 # Package subroutine.
465 # @return a list of GDAL resampling methods. These are currently:
466 # Average, Bilinear, Cubic, CubicSpline, Lanczos, Max, Med, Min, Mode, NearestNeighbour, Q1, and Q3.
468 sub ResamplingTypes {
469 return @RESAMPLING_TYPES;
472 #** @method RmdirRecursive()
477 #** @method SetCacheMax($Bytes)
478 # Package subroutine.
479 # @param Bytes New maximum amount of memory for caching within GDAL.
484 #** @method SetConfigOption($key, $value)
485 # Package subroutine.
486 # @param key A GDAL config option. Consult <a
487 # href="https://trac.osgeo.org/gdal/wiki/ConfigOptions">the GDAL
488 # documentation</a> for available options and their use.
489 # @param value A value for the option, typically 'YES', 'NO',
490 # undef, path, numeric value, or a filename.
492 sub SetConfigOption {
495 #** @method UseExceptions()
496 # Package subroutine.
497 # Use the Perl exception mechanism for GDAL messages (failures are
498 # confessed and warnings are warned) and collect the messages
499 # into \@Geo::GDAL::error. This is the default.
504 #** @method VSICurlClearCache()
506 sub VSICurlClearCache {
509 #** @method VSIFEofL()
514 #** @method VSIFOpenExL()
519 #** @method VSIGetLastErrorMsg()
521 sub VSIGetLastErrorMsg {
524 #** @method VSIGetLastErrorNo()
526 sub VSIGetLastErrorNo {
529 #** @method scalar VersionInfo($request = 'VERSION_NUM')
530 # Package subroutine.
531 # @param request A string specifying the request. Currently either
532 # "VERSION_NUM", "RELEASE_DATE", "RELEASE_NAME", or
533 # "--version". Default is "VERSION_NUM".
534 # @return Requested information.
539 #** @method scalar errstr()
540 # Package subroutine.
541 # Clear the error stack and return all generated GDAL error messages in one (possibly multiline) string.
542 # @return the chomped error stack joined with newlines.
548 return join("\n", @stack);
550 # usage: named_parameters(\@_, key value list of default parameters);
551 # returns parameters in a hash with low-case-without-_ keys
554 #** @class Geo::GDAL::AsyncReader
555 # @brief Enable asynchronous requests.
556 # @details This class is not yet documented nor tested in the GDAL Perl wrappers
557 # @todo Test and document.
559 package Geo::GDAL::AsyncReader;
561 use base qw(Geo::GDAL)
563 #** @method GetNextUpdatedRegion()
565 sub GetNextUpdatedRegion {
568 #** @method LockBuffer()
573 #** @method UnlockBuffer()
578 #** @class Geo::GDAL::Band
579 # @brief A raster band.
582 package Geo::GDAL::Band;
584 use base qw(Geo::GDAL::MajorObject Geo::GDAL)
588 # scalar (access as $band->{XSize})
593 # scalar (access as $band->{YSize})
596 #** @method AdviseRead()
601 #** @method Geo::GDAL::RasterAttributeTable AttributeTable($AttributeTable)
603 # @param AttributeTable [optional] A Geo::GDAL::RasterAttributeTable object.
604 # @return a new Geo::GDAL::RasterAttributeTable object, whose data is
605 # contained within the band.
609 SetDefaultRAT($self, $_[0]) if @_ and defined $_[0];
610 return unless defined wantarray;
611 my $r = GetDefaultRAT($self);
612 keep($r, $self) if $r;
615 #** @method list BlockSize()
618 # @return The size of a preferred i/o raster block size as a list
624 #** @method list CategoryNames(@names)
626 # @param names [optional]
631 SetRasterCategoryNames($self, \@_) if @_;
632 return unless defined wantarray;
633 my $n = GetRasterCategoryNames($self);
637 #** @method scalar Checksum($xoff = 0, $yoff = 0, $xsize = undef, $ysize = undef)
639 # Computes a checksum from the raster or a part of it.
644 # @return the checksum.
649 #** @method hashref ClassCounts($classifier, $progress = undef, $progress_data = undef)
651 # Compute the counts of cell values or number of cell values in ranges.
652 # @note Classifier is required only for float bands.
653 # @note NoData values are counted similar to other values when
654 # classifier is not defined for integer rasters.
656 # @param classifier Anonymous array of format [ $comparison,
657 # $classifier ], where $comparison is a string '<', '<=', '>', or '>='
658 # and $classifier is an anonymous array of format [ $value,
659 # $value|$classifier, $value|$classifier ], where $value is a numeric
660 # value against which the reclassified value is compared to. If the
661 # comparison returns true, then the second $value or $classifier is
662 # applied, and if not then the third $value or $classifier.
664 # In the example below, the line is divided into ranges
665 # [-inf..3), [3..5), and [5..inf], i.e., three ranges with class
666 # indexes 0, 1, and 2. Note that the indexes are used as keys for
667 # class counts and not the class values (here 1.0, 2.0, and 3.0),
668 # which are used in Geo::GDAL::Band::Reclassify.
670 # $classifier = [ '<', [5.0, [3.0, 1.0, 2.0], 3.0] ];
671 # # Howto create this $classifier from @class_boundaries:
672 # my $classifier = ['<='];
673 # my $tree = [$class_boundaries[0], 0, 1];
674 # for my $i (1 .. $#class_boundaries) {
675 # $tree = [$class_boundaries[$i], [@$tree], $i+1];
677 # push @$classifier, $tree;
679 # @return a reference to an anonymous hash, which contains the class
680 # values (indexes) as keys and the number of cells with that value or
681 # in that range as values. If the subroutine is user terminated an
687 #** @method scalar ColorInterpretation($color_interpretation)
689 # @note a.k.a. GetRasterColorInterpretation and GetColorInterpretation
690 # (get only and returns an integer), SetRasterColorInterpretation and
691 # SetColorInterpretation (set only and requires an integer)
692 # @param color_interpretation [optional] new color interpretation, one
693 # of Geo::GDAL::Band::ColorInterpretations.
694 # @return The color interpretation of this band. One of Geo::GDAL::Band::ColorInterpretations.
696 sub ColorInterpretation {
699 $ci = s2i(color_interpretation => $ci);
700 SetRasterColorInterpretation($self, $ci);
702 return unless defined wantarray;
703 i2s(color_interpretation => GetRasterColorInterpretation($self));
706 #** @method ColorInterpretations()
707 # Package subroutine.
708 # @return a list of types of color interpretation for raster
709 # bands. These are currently:
710 # AlphaBand, BlackBand, BlueBand, CyanBand, GrayIndex, GreenBand, HueBand, LightnessBand, MagentaBand, PaletteIndex, RedBand, SaturationBand, Undefined, YCbCr_CbBand, YCbCr_CrBand, YCbCr_YBand, and YellowBand.
712 sub ColorInterpretations {
713 return @COLOR_INTERPRETATIONS;
716 #** @method Geo::GDAL::ColorTable ColorTable($ColorTable)
718 # Get or set the color table of this band.
719 # @param ColorTable [optional] a Geo::GDAL::ColorTable object
720 # @return A new Geo::GDAL::ColorTable object which represents the
721 # internal color table associated with this band. Returns undef this
722 # band does not have an associated color table.
726 SetRasterColorTable($self, $_[0]) if @_ and defined $_[0];
727 return unless defined wantarray;
728 GetRasterColorTable($self);
731 #** @method ComputeBandStats($samplestep = 1)
733 # @param samplestep the row increment in computing the statistics.
734 # @note Returns uncorrected sample standard deviation.
736 # See also Geo::GDAL::Band::ComputeStatistics.
737 # @return a list (mean, stddev).
739 sub ComputeBandStats {
742 #** @method ComputeRasterMinMax($approx_ok = 0)
744 # @return arrayref MinMax = [min, max]
746 sub ComputeRasterMinMax {
749 #** @method list ComputeStatistics($approx_ok, $progress = undef, $progress_data = undef)
751 # @param approx_ok Whether it is allowed to compute the statistics
752 # based on overviews or similar.
753 # @note Returns uncorrected sample standard deviation.
755 # See also Geo::GDAL::Band::ComputeBandStats.
756 # @return a list ($min, $max, $mean, $stddev).
758 sub ComputeStatistics {
761 #** @method Geo::OGR::Layer Contours($DataSource, hashref LayerConstructor, $ContourInterval, $ContourBase, arrayref FixedLevels, $NoDataValue, $IDField, $ElevField, coderef Progress, $ProgressData)
763 # Generate contours for this raster band. This method can also be used with named parameters.
764 # @note This method is a wrapper for ContourGenerate.
769 # $dem = Geo::GDAL::Open('dem.gtiff');
770 # $contours = $dem->Band->Contours(ContourInterval => 10, ElevField => 'z');
771 # $n = $contours->GetFeatureCount;
774 # @param DataSource a Geo::OGR::DataSource object, default is a Memory data source
775 # @param LayerConstructor data for Geo::OGR::DataSource::CreateLayer, default is {Name => 'contours'}
776 # @param ContourInterval default is 100
777 # @param ContourBase default is 0
778 # @param FixedLevels a reference to a list of fixed contour levels, default is []
779 # @param NoDataValue default is undef
780 # @param IDField default is '', i.e., no field (the field is created if this is given)
781 # @param ElevField default is '', i.e., no field (the field is created if this is given)
782 # @param progress [optional] a reference to a subroutine, which will
783 # be called with parameters (number progress, string msg, progress_data)
784 # @param progress_data [optional]
789 my $p = named_parameters(\@_,
791 LayerConstructor => {Name => 'contours'},
792 ContourInterval => 100,
795 NoDataValue => undef,
799 ProgressData => undef);
800 $p->{datasource} //= Geo::OGR::GetDriver('Memory')->CreateDataSource('ds');
801 $p->{layerconstructor}->{Schema} //= {};
802 $p->{layerconstructor}->{Schema}{Fields} //= [];
804 unless ($p->{idfield} =~ /^[+-]?\d+$/ or $fields{$p->{idfield}}) {
805 push @{$p->{layerconstructor}->{Schema}{Fields}}, {Name => $p->{idfield}, Type => 'Integer'};
807 unless ($p->{elevfield} =~ /^[+-]?\d+$/ or $fields{$p->{elevfield}}) {
808 my $type = $self->DataType() =~ /Float/ ? 'Real' : 'Integer';
809 push @{$p->{layerconstructor}->{Schema}{Fields}}, {Name => $p->{elevfield}, Type => $type};
811 my $layer = $p->{datasource}->CreateLayer($p->{layerconstructor});
812 my $schema = $layer->GetLayerDefn;
813 for ('idfield', 'elevfield') {
814 $p->{$_} = $schema->GetFieldIndex($p->{$_}) unless $p->{$_} =~ /^[+-]?\d+$/;
816 $p->{progressdata} = 1 if $p->{progress} and not defined $p->{progressdata};
817 ContourGenerate($self, $p->{contourinterval}, $p->{contourbase}, $p->{fixedlevels},
818 $p->{nodatavalue}, $layer, $p->{idfield}, $p->{elevfield},
819 $p->{progress}, $p->{progressdata});
823 #** @method CreateMaskBand(@flags)
825 # @note May invalidate any previous mask band obtained with Geo::GDAL::Band::GetMaskBand.
827 # @param flags one or more mask flags. The flags are Geo::GDAL::Band::MaskFlags.
832 if (@_ and $_[0] =~ /^\d$/) {
836 carp "Unknown mask flag: '$flag'." unless $MASK_FLAGS{$flag};
837 $f |= $MASK_FLAGS{$flag};
840 $self->_CreateMaskBand($f);
843 #** @method scalar DataType()
845 # @return The data type of this band. One of Geo::GDAL::DataTypes.
849 return i2s(data_type => $self->{DataType});
852 #** @method Geo::GDAL::Dataset Dataset()
854 # @return The dataset which this band belongs to.
861 #** @method scalar DeleteNoDataValue()
864 sub DeleteNoDataValue {
867 #** @method Geo::GDAL::Band Distance(%params)
869 # Compute distances to specific cells of this raster.
870 # @param params Named parameters:
871 # - \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.
872 # - \a Options Hash of options. Options are:
873 # - \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.
874 # - \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.
875 # - \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.
876 # - \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).
877 # - \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.
878 # - \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.
879 # - \a DataType The data type for the result if it is not given.
880 # - \a Progress Progress function.
881 # - \a ProgressData Additional parameter for the progress function.
883 # @note This GDAL function behind this API is called GDALComputeProximity.
885 # @return The distance raster.
889 my $p = named_parameters(\@_, Distance => undef, Options => undef, Progress => undef, ProgressData => undef);
890 for my $key (keys %{$p->{options}}) {
891 $p->{options}{uc($key)} = $p->{options}{$key};
893 $p->{options}{TYPE} //= $p->{options}{DATATYPE} //= 'Float32';
894 unless ($p->{distance}) {
895 my ($w, $h) = $self->Size;
896 $p->{distance} = Geo::GDAL::Driver('MEM')->Create(Name => 'distance', Width => $w, Height => $h, Type => $p->{options}{TYPE})->Band;
898 Geo::GDAL::ComputeProximity($self, $p->{distance}, $p->{options}, $p->{progress}, $p->{progressdata});
899 return $p->{distance};
902 #** @method Domains()
908 #** @method Fill($real_part, $imag_part = 0.0)
910 # Fill the band with a constant value.
911 # @param real_part Real component of fill value.
912 # @param imag_part Imaginary component of fill value.
918 #** @method FillNoData($mask, $max_search_dist, $smoothing_iterations, $options, coderef progress, $progress_data)
920 # Interpolate values for cells in this raster. The cells to fill
921 # should be marked in the mask band with zero.
923 # @param mask [optional] a mask band indicating cells to be interpolated (zero valued) (default is to get it with Geo::GDAL::Band::GetMaskBand).
924 # @param max_search_dist [optional] the maximum number of cells to
925 # search in all directions to find values to interpolate from (default is 10).
926 # @param smoothing_iterations [optional] the number of 3x3 smoothing filter passes to run (0 or more) (default is 0).
927 # @param options [optional] A reference to a hash. No options have been defined so far for this algorithm (default is {}).
928 # @param progress [optional] a reference to a subroutine, which will
929 # be called with parameters (number progress, string msg, progress_data) (default is undef).
930 # @param progress_data [optional] (default is undef).
932 # <a href="http://www.gdal.org/gdal__alg_8h.html">Documentation for GDAL algorithms</a>
937 #** @method FlushCache()
939 # Write cached data to disk. There is usually no need to call this
945 #** @method scalar GetBandNumber()
947 # @return The index of this band in the parent dataset list of bands.
952 #** @method GetBlockSize()
957 #** @method list GetDefaultHistogram($force = 1, coderef progress = undef, $progress_data = undef)
959 # @param force true to force the computation
960 # @param progress [optional] a reference to a subroutine, which will
961 # be called with parameters (number progress, string msg, progress_data)
962 # @param progress_data [optional]
963 # @note See Note in Geo::GDAL::Band::GetHistogram.
964 # @return a list: ($min, $max, arrayref histogram).
966 sub GetDefaultHistogram {
969 #** @method list GetHistogram(%parameters)
971 # Compute histogram from the raster.
972 # @param parameters Named parameters:
973 # - \a Min the lower bound, default is -0.5
974 # - \a Max the upper bound, default is 255.5
975 # - \a Buckets the number of buckets in the histogram, default is 256
976 # - \a IncludeOutOfRange whether to use the first and last values in the returned list
977 # for out of range values, default is false;
978 # the bucket size is (Max-Min) / Buckets if this is false and
979 # (Max-Min) / (Buckets-2) if this is true
980 # - \a ApproxOK if histogram can be computed from overviews, default is false
981 # - \a Progress an optional progress function, the default is undef
982 # - \a ProgressData data for the progress function, the default is undef
983 # @note Histogram counts are treated as strings in the bindings to be
984 # able to use large integers (if GUIntBig is larger than Perl IV). In
985 # practice this is only important if you have a 32 bit machine and
986 # very large bucket counts. In those cases it may also be necessary to
988 # @return a list which contains the count of values in each bucket
992 my $p = named_parameters(\@_,
996 IncludeOutOfRange => 0,
999 ProgressData => undef);
1000 $p->{progressdata} = 1 if $p->{progress} and not defined $p->{progressdata};
1001 _GetHistogram($self, $p->{min}, $p->{max}, $p->{buckets},
1002 $p->{includeoutofrange}, $p->{approxok},
1003 $p->{progress}, $p->{progressdata});
1006 #** @method Geo::GDAL::Band GetMaskBand()
1008 # @return the mask band associated with this
1013 my $band = _GetMaskBand($self);
1017 #** @method list GetMaskFlags()
1019 # @return the mask flags of the mask band associated with this
1020 # band. The flags are one or more of Geo::GDAL::Band::MaskFlags.
1024 my $f = $self->_GetMaskFlags;
1026 for my $flag (keys %MASK_FLAGS) {
1027 push @f, $flag if $f & $MASK_FLAGS{$flag};
1029 return wantarray ? @f : $f;
1032 #** @method scalar GetMaximum()
1034 # @note Call Geo::GDAL::Band::ComputeStatistics before calling
1035 # GetMaximum to make sure the value is computed.
1037 # @return statistical minimum of the band or undef if statistics are
1038 # not kept or computed in scalar context. In list context returns the
1039 # maximum value or a (kind of) maximum value supported by the data
1040 # type and a boolean value, which indicates which is the case (true is
1041 # first, false is second).
1046 #** @method scalar GetMinimum()
1048 # @note Call Geo::GDAL::Band::ComputeStatistics before calling
1049 # GetMinimum to make sure the value is computed.
1051 # @return statistical minimum of the band or undef if statistics are
1052 # not kept or computed in scalar context. In list context returns the
1053 # minimum value or a (kind of) minimum value supported by the data
1054 # type and a boolean value, which indicates which is the case (true is
1055 # first, false is second).
1060 #** @method Geo::GDAL::Band GetOverview($index)
1062 # @param index 0..GetOverviewCount-1
1063 # @return a Geo::GDAL::Band object, which represents the internal
1064 # overview band, or undef. if the index is out of bounds.
1067 my ($self, $index) = @_;
1068 my $band = _GetOverview($self, $index);
1072 #** @method scalar GetOverviewCount()
1074 # @return the number of overviews available of the band.
1076 sub GetOverviewCount {
1079 #** @method list GetStatistics($approx_ok, $force)
1081 # @param approx_ok Whether it is allowed to compute the statistics
1082 # based on overviews or similar.
1083 # @param force Whether to force scanning of the whole raster.
1084 # @note Uses Geo::GDAL::Band::ComputeStatistics internally.
1086 # @return a list ($min, $max, $mean, $stddev).
1091 #** @method HasArbitraryOverviews()
1093 # @return true or false.
1095 sub HasArbitraryOverviews {
1098 #** @method list MaskFlags()
1099 # Package subroutine.
1100 # @return the list of mask flags. These are
1101 # - \a AllValid: There are no invalid cell, all mask values will be 255.
1102 # When used this will normally be the only flag set.
1103 # - \a PerDataset: The mask band is shared between all bands on the dataset.
1104 # - \a Alpha: The mask band is actually an alpha band and may have values
1105 # other than 0 and 255.
1106 # - \a NoData: Indicates the mask is actually being generated from NoData values.
1107 # (mutually exclusive of Alpha).
1110 my @f = sort {$MASK_FLAGS{$a} <=> $MASK_FLAGS{$b}} keys %MASK_FLAGS;
1114 #** @method scalar NoDataValue($NoDataValue)
1116 # Get or set the "no data" value.
1117 # @param NoDataValue [optional]
1118 # @note $band->NoDataValue(undef) sets the NoData value to the
1119 # Posix floating point maximum. Use Geo::GDAL::Band::DeleteNoDataValue
1120 # to stop this band using a NoData value.
1121 # @return The NoData value or undef in scalar context. An undef
1122 # value indicates that there is no NoData value associated with this
1128 if (defined $_[0]) {
1129 SetNoDataValue($self, $_[0]);
1131 SetNoDataValue($self, POSIX::FLT_MAX); # hopefully an "out of range" value
1134 GetNoDataValue($self);
1137 #** @method scalar PackCharacter()
1139 # @return The character to use in Perl pack and unpack for the data of this band.
1143 return Geo::GDAL::PackCharacter($self->DataType);
1146 #** @method Piddle($piddle, $xoff = 0, $yoff = 0, $xsize = <width>, $ysize = <height>, $xdim, $ydim)
1148 # Read or write band data from/into a piddle.
1150 # \note The PDL module must be available for this method to work. Also, you
1151 # should 'use PDL' in the code that you use this method.
1153 # @param piddle [only when writing] The piddle from which to read the data to be written into the band.
1154 # @param xoff, yoff The offset for data in the band, default is top left (0, 0).
1155 # @param xsize, ysize [optional] The size of the window in the band.
1156 # @param xdim, ydim [optional, only when reading from a band] The size of the piddle to create.
1157 # @return A new piddle when reading from a band (no not use when writing into a band).
1160 # TODO: add Piddle sub to dataset too to make Width x Height x Bands piddles
1161 error("PDL is not available.") unless $Geo::GDAL::HAVE_PDL;
1163 my $t = $self->{DataType};
1164 unless (defined wantarray) {
1166 error("The datatype of the Piddle and the band do not match.")
1167 unless $PDL2DATATYPE{$pdl->get_datatype} == $t;
1168 my ($xoff, $yoff, $xsize, $ysize) = @_;
1171 my $data = $pdl->get_dataref();
1172 my ($xdim, $ydim) = $pdl->dims();
1173 if ($xdim > $self->{XSize} - $xoff) {
1174 warn "Piddle XSize too large ($xdim) for this raster band (width = $self->{XSize}, offset = $xoff).";
1175 $xdim = $self->{XSize} - $xoff;
1177 if ($ydim > $self->{YSize} - $yoff) {
1178 $ydim = $self->{YSize} - $yoff;
1179 warn "Piddle YSize too large ($ydim) for this raster band (height = $self->{YSize}, offset = $yoff).";
1183 $self->_WriteRaster($xoff, $yoff, $xsize, $ysize, $data, $xdim, $ydim, $t, 0, 0);
1186 my ($xoff, $yoff, $xsize, $ysize, $xdim, $ydim, $alg) = @_;
1189 $xsize //= $self->{XSize} - $xoff;
1190 $ysize //= $self->{YSize} - $yoff;
1193 $alg //= 'NearestNeighbour';
1194 $alg = s2i(rio_resampling => $alg);
1195 my $buf = $self->_ReadRaster($xoff, $yoff, $xsize, $ysize, $xdim, $ydim, $t, 0, 0, $alg);
1197 my $datatype = $DATATYPE2PDL{$t};
1198 error("The band datatype is not supported by PDL.") if $datatype < 0;
1199 $pdl->set_datatype($datatype);
1200 $pdl->setdims([$xdim, $ydim]);
1201 my $data = $pdl->get_dataref();
1204 # FIXME: we want approximate equality since no data value can be very large floating point value
1205 my $bad = GetNoDataValue($self);
1206 return $pdl->setbadif($pdl == $bad) if defined $bad;
1210 #** @method Geo::OGR::Layer Polygonize(%params)
1212 # Polygonize this raster band.
1214 # @param params Named parameters:
1215 # - \a Mask A raster band, which is used as a mask to select polygonized areas. Default is undef.
1216 # - \a OutLayer A vector layer into which the polygons are written. If not given, an in-memory layer 'polygonized' is created and returned.
1217 # - \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'.
1218 # - \a Options Hash or list of options. Connectedness can be set to 8
1219 # to use 8-connectedness, otherwise 4-connectedness is
1220 # used. ForceIntPixel can be set to 1 to force using a 32 bit int buffer
1221 # for cell values in the process. If this is not set and the data type
1222 # of this raster does not fit into a 32 bit int buffer, a 32 bit float
1224 # - \a Progress Progress function.
1225 # - \a ProgressData Additional parameter for the progress function.
1227 # @return Output vector layer.
1231 my $p = named_parameters(\@_, Mask => undef, OutLayer => undef, PixValField => 'val', Options => undef, Progress => undef, ProgressData => undef);
1232 my %known_options = (Connectedness => 1, ForceIntPixel => 1, DATASET_FOR_GEOREF => 1, '8CONNECTED' => 1);
1233 for my $option (keys %{$p->{options}}) {
1234 error(1, $option, \%known_options) unless exists $known_options{$option};
1236 my $dt = $self->DataType;
1237 my %leInt32 = (Byte => 1, Int16 => 1, Int32 => 1, UInt16 => 1);
1238 my $leInt32 = $leInt32{$dt};
1239 $dt = $dt =~ /Float/ ? 'Real' : 'Integer';
1240 $p->{outlayer} //= Geo::OGR::Driver('Memory')->Create()->
1241 CreateLayer(Name => 'polygonized',
1242 Fields => [{Name => 'val', Type => $dt},
1243 {Name => 'geom', Type => 'Polygon'}]);
1244 $p->{pixvalfield} = $p->{outlayer}->GetLayerDefn->GetFieldIndex($p->{pixvalfield});
1245 $p->{options}{'8CONNECTED'} = 1 if $p->{options}{Connectedness} && $p->{options}{Connectedness} == 8;
1246 if ($leInt32 || $p->{options}{ForceIntPixel}) {
1247 Geo::GDAL::_Polygonize($self, $p->{mask}, $p->{outlayer}, $p->{pixvalfield}, $p->{options}, $p->{progress}, $p->{progressdata});
1249 Geo::GDAL::FPolygonize($self, $p->{mask}, $p->{outlayer}, $p->{pixvalfield}, $p->{options}, $p->{progress}, $p->{progressdata});
1251 set the srs of the outlayer if it was created here
1252 return $p->{outlayer};
1255 #** @method RasterAttributeTable()
1257 sub RasterAttributeTable {
1260 #** @method scalar ReadRaster(%params)
1262 # Read data from the band.
1264 # @param params Named parameters:
1265 # - \a XOff x offset (cell coordinates) (default is 0)
1266 # - \a YOff y offset (cell coordinates) (default is 0)
1267 # - \a XSize width of the area to read (default is the width of the band)
1268 # - \a YSize height of the area to read (default is the height of the band)
1269 # - \a BufXSize (default is undef, i.e., the same as XSize)
1270 # - \a BufYSize (default is undef, i.e., the same as YSize)
1271 # - \a BufType data type of the buffer (default is the data type of the band)
1272 # - \a BufPixelSpace (default is 0)
1273 # - \a BufLineSpace (default is 0)
1274 # - \a ResampleAlg one of Geo::GDAL::RIOResamplingTypes (default is 'NearestNeighbour'),
1275 # - \a Progress reference to a progress function (default is undef)
1276 # - \a ProgressData (default is undef)
1278 # <a href="http://www.gdal.org/classGDALDataset.html">Entry in GDAL docs (method RasterIO)</a>
1279 # @return a buffer, open the buffer with \a unpack function of Perl. See Geo::GDAL::Band::PackCharacter.
1283 my ($width, $height) = $self->Size;
1284 my ($type) = $self->DataType;
1285 my $p = named_parameters(\@_,
1295 ResampleAlg => 'NearestNeighbour',
1297 ProgressData => undef
1299 $p->{resamplealg} = s2i(rio_resampling => $p->{resamplealg});
1300 $p->{buftype} = s2i(data_type => $p->{buftype}, 1);
1301 $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});
1304 #** @method array reference ReadTile($xoff = 0, $yoff = 0, $xsize = <width>, $ysize = <height>)
1306 # Read band data into a Perl array.
1308 # \note Accessing band data in this way is slow. Consider using PDL and Geo::GDAL::Band::Piddle.
1310 # Usage example (print the data from a band):
1312 # print "@$_\n" for ( @{ $band->ReadTile() } );
1314 # Another usage example (process the data of a large dataset that has one band):
1316 # my($W,$H) = $dataset->Band()->Size();
1317 # my($xoff,$yoff,$w,$h) = (0,0,200,200);
1319 # if ($xoff >= $W) {
1322 # last if $yoff >= $H;
1324 # my $data = $dataset->Band(1)->ReadTile($xoff,$yoff,min($W-$xoff,$w),min($H-$yoff,$h));
1325 # # add your data processing code here
1326 # $dataset->Band(1)->WriteTile($data,$xoff,$yoff);
1331 # return $_[0] < $_[1] ? $_[0] : $_[1];
1334 # @param xoff Number of cell to skip before starting to read from a row. Pixels are read from left to right.
1335 # @param yoff Number of cells to skip before starting to read from a column. Pixels are read from top to bottom.
1336 # @param xsize Number of cells to read from each row.
1337 # @param ysize Number of cells to read from each column.
1338 # @return a two-dimensional Perl array, organizes as data->[y][x], y =
1339 # 0..height-1, x = 0..width-1. I.e., y is row and x is column.
1342 my($self, $xoff, $yoff, $xsize, $ysize, $w_tile, $h_tile, $alg) = @_;
1345 $xsize //= $self->{XSize} - $xoff;
1346 $ysize //= $self->{YSize} - $yoff;
1349 $alg //= 'NearestNeighbour';
1350 $alg = s2i(rio_resampling => $alg);
1351 my $t = $self->{DataType};
1352 my $buf = $self->_ReadRaster($xoff, $yoff, $xsize, $ysize, $w_tile, $h_tile, $t, 0, 0, $alg);
1353 my $pc = Geo::GDAL::PackCharacter($t);
1354 my $w = $w_tile * Geo::GDAL::GetDataTypeSize($t)/8;
1357 for my $y (0..$h_tile-1) {
1358 my @d = unpack($pc."[$w_tile]", substr($buf, $offset, $w));
1365 #** @method Reclassify($classifier, $progress = undef, $progress_data = undef)
1367 # Reclassify the cells in the band.
1368 # @note NoData values in integer rasters are reclassified if
1369 # explicitly specified in the hash classifier. However, they are not
1370 # reclassified to the default value, if one is specified. In real
1371 # valued rasters nodata cells are not reclassified.
1372 # @note If the subroutine is user terminated or the classifier is
1373 # incorrect, already reclassified cells will stay reclassified but an
1375 # @param classifier For integer rasters an anonymous hash, which
1376 # contains old class values as keys and new class values as values, or
1377 # an array classifier as in Geo::GDAL::Band::ClassCounts. In a hash
1378 # classifier a special key '*' (star) can be used as default, to act
1379 # as a fallback new class value. For real valued rasters the
1380 # classifier is as in Geo::GDAL::Band::ClassCounts.
1385 #** @method RegenerateOverview(Geo::GDAL::Band overview, $resampling, coderef progress, $progress_data)
1387 # @param overview a Geo::GDAL::Band object for the overview.
1388 # @param resampling [optional] the resampling method (one of Geo::GDAL::RIOResamplingTypes) (default is Average).
1389 # @param progress [optional] a reference to a subroutine, which will
1390 # be called with parameters (number progress, string msg, progress_data)
1391 # @param progress_data [optional]
1393 sub RegenerateOverview {
1395 #Geo::GDAL::Band overview, scalar resampling, subref callback, scalar callback_data
1397 Geo::GDAL::RegenerateOverview($self, @p);
1400 #** @method RegenerateOverviews(arrayref overviews, $resampling, coderef progress, $progress_data)
1402 # @todo This is not yet available
1404 # @param overviews a list of Geo::GDAL::Band objects for the overviews.
1405 # @param resampling [optional] the resampling method (one of Geo::GDAL::RIOResamplingTypes) (default is Average).
1406 # @param progress [optional] a reference to a subroutine, which will
1407 # be called with parameters (number progress, string msg, progress_data)
1408 # @param progress_data [optional]
1410 sub RegenerateOverviews {
1412 #arrayref overviews, scalar resampling, subref callback, scalar callback_data
1414 Geo::GDAL::RegenerateOverviews($self, @p);
1417 #** @method ScaleAndOffset($scale, $offset)
1419 # Scale and offset are used to transform raw cell values into the
1420 # units returned by GetUnits(). The conversion function is:
1422 # Units value = (raw value * scale) + offset
1424 # @return a list ($scale, $offset), the values are undefined if they
1426 # @since version 1.9 of the bindings.
1428 sub ScaleAndOffset {
1430 SetScale($self, $_[0]) if @_ > 0 and defined $_[0];
1431 SetOffset($self, $_[1]) if @_ > 1 and defined $_[1];
1432 return unless defined wantarray;
1433 my $scale = GetScale($self);
1434 my $offset = GetOffset($self);
1435 return ($scale, $offset);
1438 #** @method list SetDefaultHistogram($min, $max, $histogram)
1442 # @note See Note in Geo::GDAL::Band::GetHistogram.
1443 # @param histogram reference to an array containing the histogram
1445 sub SetDefaultHistogram {
1448 #** @method SetStatistics($min, $max, $mean, $stddev)
1450 # Save the statistics of the band if possible (the format can save
1451 # arbitrary metadata).
1460 #** @method Geo::GDAL::Band Sieve(%params)
1462 # Remove small areas by merging them into the largest neighbour area.
1463 # @param params Named parameters:
1464 # - \a Mask A raster band, which is used as a mask to select sieved areas. Default is undef.
1465 # - \a Dest A raster band into which the result is written. If not given, an new in-memory raster band is created and returned.
1466 # - \a Threshold The smallest area size (in number of cells) which are not sieved away.
1467 # - \a Options Hash or list of options. {Connectedness => 4} can be specified to use 4-connectedness, otherwise 8-connectedness is used.
1468 # - \a Progress Progress function.
1469 # - \a ProgressData Additional parameter for the progress function.
1471 # @return The filtered raster band.
1475 my $p = named_parameters(\@_, Mask => undef, Dest => undef, Threshold => 10, Options => undef, Progress => undef, ProgressData => undef);
1476 unless ($p->{dest}) {
1477 my ($w, $h) = $self->Size;
1478 $p->{dest} = Geo::GDAL::Driver('MEM')->Create(Name => 'sieved', Width => $w, Height => $h, Type => $self->DataType)->Band;
1481 if ($p->{options}{Connectedness}) {
1482 $c = $p->{options}{Connectedness};
1483 delete $p->{options}{Connectedness};
1485 Geo::GDAL::SieveFilter($self, $p->{mask}, $p->{dest}, $p->{threshold}, $c, $p->{options}, $p->{progress}, $p->{progressdata});
1489 #** @method list Size()
1491 # @return The size of the band as a list (width, height).
1495 return ($self->{XSize}, $self->{YSize});
1498 #** @method Unit($type)
1500 # @param type [optional] the unit (a string).
1501 # @note $band->Unit(undef) sets the unit value to an empty string.
1502 # @return the unit (a string).
1503 # @since version 1.9 of the bindings.
1510 SetUnitType($self, $unit);
1512 return unless defined wantarray;
1516 #** @method WriteRaster(%params)
1518 # Write data into the band.
1520 # @param params Named parameters:
1521 # - \a XOff x offset (cell coordinates) (default is 0)
1522 # - \a YOff y offset (cell coordinates) (default is 0)
1523 # - \a XSize width of the area to write (default is the width of the band)
1524 # - \a YSize height of the area to write (default is the height of the band)
1525 # - \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.
1526 # - \a BufXSize (default is undef, i.e., the same as XSize)
1527 # - \a BufYSize (default is undef, i.e., the same as YSize)
1528 # - \a BufType data type of the buffer (default is the data type of the band)
1529 # - \a BufPixelSpace (default is 0)
1530 # - \a BufLineSpace (default is 0)
1532 # <a href="http://www.gdal.org/classGDALDataset.html">Entry in GDAL docs (method RasterIO)</a>
1536 my ($width, $height) = $self->Size;
1537 my ($type) = $self->DataType;
1538 my $p = named_parameters(\@_,
1550 confess "Usage: \$band->WriteRaster( Buf => \$data, ... )" unless defined $p->{buf};
1551 $p->{buftype} = s2i(data_type => $p->{buftype}, 1);
1552 $self->_WriteRaster($p->{xoff},$p->{yoff},$p->{xsize},$p->{ysize},$p->{buf},$p->{bufxsize},$p->{bufysize},$p->{buftype},$p->{bufpixelspace},$p->{buflinespace});
1555 #** @method WriteTile($data, $xoff = 0, $yoff = 0)
1557 # Write band data from a Perl array.
1559 # \note Accessing band data in this way is slow. Consider using PDL and Geo::GDAL::Band::Piddle.
1561 # @param data A two-dimensional Perl array, organizes as data->[y][x], y =
1562 # 0..height-1, x = 0..width-1.
1568 my($self, $data, $xoff, $yoff) = @_;
1571 error('The data must be in a two-dimensional array') unless ref $data eq 'ARRAY' && ref $data->[0] eq 'ARRAY';
1572 my $xsize = @{$data->[0]};
1573 if ($xsize > $self->{XSize} - $xoff) {
1574 warn "Buffer XSize too large ($xsize) for this raster band (width = $self->{XSize}, offset = $xoff).";
1575 $xsize = $self->{XSize} - $xoff;
1577 my $ysize = @{$data};
1578 if ($ysize > $self->{YSize} - $yoff) {
1579 $ysize = $self->{YSize} - $yoff;
1580 warn "Buffer YSize too large ($ysize) for this raster band (height = $self->{YSize}, offset = $yoff).";
1582 my $pc = Geo::GDAL::PackCharacter($self->{DataType});
1583 for my $i (0..$ysize-1) {
1584 my $scanline = pack($pc."[$xsize]", @{$data->[$i]});
1585 $self->WriteRaster( $xoff, $yoff+$i, $xsize, 1, $scanline );
1589 #** @class Geo::GDAL::ColorTable
1590 # @brief A color table from a raster band or a color table, which can be used for a band.
1593 package Geo::GDAL::ColorTable;
1595 use base qw(Geo::GDAL)
1597 #** @method Geo::GDAL::ColorTable Clone()
1599 # Clone an existing color table.
1600 # @return a new Geo::GDAL::ColorTable object
1605 #** @method list Color($index, @color)
1607 # Get or set a color in this color table.
1608 # @param index The index of the color in the table. Note that the
1609 # color table may expand if the index is larger than the current max
1610 # index of this table and a color is given. An attempt to retrieve a
1611 # color out of the current size of the table causes an error.
1612 # @param color [optional] The color, either a list or a reference to a
1613 # list. If the list is too short or has undef values, the undef values
1614 # are taken as 0 except for alpha, which is taken as 255.
1615 # @note A color is an array of four integers having a value between 0
1616 # and 255: (gray, red, cyan or hue; green, magenta, or lightness;
1617 # blue, yellow, or saturation; alpha or blackband)
1618 # @return A color, in list context a list and in scalar context a reference to an anonymous array.
1623 #** @method list Colors(@colors)
1625 # Get or set the colors in this color table.
1626 # @note The color table will expand to the size of the input list but
1627 # it will not shrink.
1628 # @param colors [optional] A list of all colors (a list of lists) for this color table.
1629 # @return A list of colors (a list of lists).
1634 #** @method CreateColorRamp($start_index, arrayref start_color, $end_index, arrayref end_color)
1636 # @param start_index
1637 # @param start_color
1641 sub CreateColorRamp {
1644 #** @method scalar GetCount()
1646 # @return The number of colors in this color table.
1651 #** @method scalar GetPaletteInterpretation()
1653 # @return palette interpretation (string)
1655 sub GetPaletteInterpretation {
1657 return i2s(palette_interpretation => GetPaletteInterpretation($self));
1660 #** @method Geo::GDAL::ColorTable new($GDALPaletteInterp = 'RGB')
1662 # Create a new empty color table.
1663 # @return a new Geo::GDAL::ColorTable object
1668 $pi = s2i(palette_interpretation => $pi);
1669 my $self = Geo::GDALc::new_ColorTable($pi);
1670 bless $self, $pkg if defined($self);
1673 #** @class Geo::GDAL::Dataset
1674 # @brief A set of associated raster bands or vector layer source.
1677 package Geo::GDAL::Dataset;
1679 use base qw(Geo::GDAL::MajorObject Geo::GDAL)
1681 #** @attr $RasterCount
1682 # scalar (access as $dataset->{RasterCount})
1685 #** @attr $RasterXSize
1686 # scalar (access as $dataset->{RasterXSize})
1689 #** @attr $RasterYSize
1690 # scalar (access as $dataset->{RasterYSize})
1693 #** @method AddBand($datatype = 'Byte', hashref options = {})
1695 # Add a new band to the dataset. The driver must support the action.
1696 # @param datatype GDAL raster cell data type (one of those listed by Geo::GDAL::DataTypes).
1697 # @param options reference to a hash of format specific options.
1698 # @return The added band.
1701 my ($self, $type, $options) = @_;
1703 $type = s2i(data_type => $type);
1704 $self->_AddBand($type, $options);
1705 return unless defined wantarray;
1706 return $self->GetRasterBand($self->{RasterCount});
1709 #** @method AdviseRead()
1714 #** @method Geo::GDAL::Band Band($index)
1716 # Create a band object for the band within the dataset.
1717 # @note a.k.a. GetRasterBand
1718 # @param index 1...RasterCount, default is 1.
1719 # @return a new Geo::GDAL::Band object
1724 #** @method list Bands()
1726 # @return a list of new Geo::GDAL::Band objects
1731 for my $i (1..$self->{RasterCount}) {
1732 push @bands, GetRasterBand($self, $i);
1737 #** @method BuildOverviews($resampling, arrayref overviews, coderef progress, $progress_data)
1739 # @param resampling the resampling method, one of Geo::GDAL::RIOResamplingTypes.
1740 # @param overviews The list of overview decimation factors to
1741 # build. For example [2,4,8].
1742 # @param progress [optional] a reference to a subroutine, which will
1743 # be called with parameters (number progress, string msg, progress_data)
1744 # @param progress_data [optional]
1746 sub BuildOverviews {
1749 $p[0] = uc($p[0]) if $p[0];
1751 $self->_BuildOverviews(@p);
1753 confess(last_error()) if $@;
1756 #** @method Geo::GDAL::Dataset BuildVRT($Dest, arrayref Sources, hashref Options, coderef progress, $progress_data)
1758 # Build a virtual dataset from a set of datasets.
1759 # @param Dest Destination raster dataset definition string (typically
1760 # filename), or an object, which implements write and close.
1761 # @param Sources A list of filenames of input datasets or a list of
1763 # @param Options See section \ref index_processing_options.
1764 # @return Dataset object
1766 # @note This subroutine is imported into the main namespace if Geo::GDAL
1767 # is use'd with qw/:all/.
1770 my ($dest, $sources, $options, $progress, $progress_data) = @_;
1771 $options = Geo::GDAL::GDALBuildVRTOptions->new(make_processing_options($options));
1772 error("Usage: Geo::GDAL::DataSet::BuildVRT(\$vrt_file_name, \\\@sources)")
1773 unless ref $sources eq 'ARRAY' && defined $sources->[0];
1774 unless (blessed($dest)) {
1775 if (blessed($sources->[0])) {
1776 return Geo::GDAL::wrapper_GDALBuildVRT_objects($dest, $sources, $options, $progress, $progress_data);
1778 return Geo::GDAL::wrapper_GDALBuildVRT_names($dest, $sources, $options, $progress, $progress_data);
1781 if (blessed($sources->[0])) {
1782 return stdout_redirection_wrapper(
1784 \&Geo::GDAL::wrapper_GDALBuildVRT_objects,
1785 $options, $progress, $progress_data);
1787 return stdout_redirection_wrapper(
1789 \&Geo::GDAL::wrapper_GDALBuildVRT_names,
1790 $options, $progress, $progress_data);
1795 #** @method CommitTransaction()
1797 sub CommitTransaction {
1800 #** @method Geo::GDAL::ColorTable ComputeColorTable(%params)
1802 # Compute a color table from an RGB image
1803 # @param params Named parameters:
1804 # - \a Red The red band, the default is to use the red band of this dataset.
1805 # - \a Green The green band, the default is to use the green band of this dataset.
1806 # - \a Blue The blue band, the default is to use the blue band of this dataset.
1807 # - \a NumColors The number of colors in the computed color table. Default is 256.
1808 # - \a Progress reference to a progress function (default is undef)
1809 # - \a ProgressData (default is undef)
1810 # - \a Method The computation method. The default and currently only option is the median cut algorithm.
1812 # @return a new color table object.
1814 sub ComputeColorTable {
1816 my $p = named_parameters(\@_,
1822 ProgressData => undef,
1823 Method => 'MedianCut');
1824 for my $b ($self->Bands) {
1825 for my $cion ($b->ColorInterpretation) {
1826 if ($cion eq 'RedBand') { $p->{red} //= $b; last; }
1827 if ($cion eq 'GreenBand') { $p->{green} //= $b; last; }
1828 if ($cion eq 'BlueBand') { $p->{blue} //= $b; last; }
1831 my $ct = Geo::GDAL::ColorTable->new;
1832 Geo::GDAL::ComputeMedianCutPCT($p->{red},
1836 $ct, $p->{progress},
1837 $p->{progressdata});
1841 #** @method Geo::OGR::Layer CopyLayer($layer, $name, hashref options = undef)
1843 # @param layer A Geo::OGR::Layer object to be copied.
1844 # @param name A name for the new layer.
1845 # @param options A ref to a hash of format specific options.
1846 # @return a new Geo::OGR::Layer object.
1851 #** @method Geo::OGR::Layer CreateLayer(%params)
1853 # @brief Create a new vector layer into this dataset.
1855 # @param %params Named parameters:
1856 # - \a Name (scalar) name for the new layer.
1857 # - \a Fields (array reference) a list of (scalar and geometry) field definitions as in
1858 # Geo::OGR::Layer::CreateField.
1859 # - \a ApproxOK (boolean value, default is true) a flag, which is forwarded to Geo::OGR::Layer::CreateField.
1860 # - \a Options (hash reference) driver specific hash of layer creation options.
1861 # - \a Schema (hash reference, deprecated, use \a Fields and \a Name) may contain keys Name, Fields, GeomFields, GeometryType.
1862 # - \a SRS (scalar) the spatial reference for the default geometry field.
1863 # - \a GeometryType (scalar) the type of the default geometry field
1864 # (if only one geometry field). Default is 'Unknown'.
1866 # @note If Fields or Schema|Fields is not given, a default geometry
1867 # field (Name => '', GeometryType => 'Unknown') is created. If it is
1868 # given and it contains spatial fields, both GeometryType and SRS are
1869 # ignored. The type can be also set with the named parameter.
1873 # my $roads = Geo::OGR::Driver('Memory')->Create('road')->
1875 # Fields => [ { Name => 'class',
1876 # Type => 'Integer' },
1878 # Type => 'LineString25D' } ] );
1881 # @note Many formats allow only one spatial field, which currently
1882 # requires the use of GeometryType.
1884 # @return a new Geo::OGR::Layer object.
1888 my $p = named_parameters(\@_,
1891 GeometryType => 'Unknown',
1896 error("The 'Fields' argument must be an array reference.") if $p->{fields} && ref($p->{fields}) ne 'ARRAY';
1897 if (defined $p->{schema}) {
1898 my $s = $p->{schema};
1899 $p->{geometrytype} = $s->{GeometryType} if exists $s->{GeometryType};
1900 $p->{fields} = $s->{Fields} if exists $s->{Fields};
1901 $p->{name} = $s->{Name} if exists $s->{Name};
1903 $p->{fields} = [] unless ref($p->{fields}) eq 'ARRAY';
1904 # if fields contains spatial fields, then do not create default one
1905 for my $f (@{$p->{fields}}) {
1906 error("Field definitions must be hash references.") unless ref $f eq 'HASH';
1907 if ($f->{GeometryType} || ($f->{Type} && s_exists(geometry_type => $f->{Type}))) {
1908 $p->{geometrytype} = 'None';
1912 my $gt = s2i(geometry_type => $p->{geometrytype});
1913 my $layer = _CreateLayer($self, $p->{name}, $p->{srs}, $gt, $p->{options});
1914 for my $f (@{$p->{fields}}) {
1915 $layer->CreateField($f);
1917 keep($layer, $self);
1920 #** @method CreateMaskBand()
1922 # Add a mask band to the dataset.
1924 sub CreateMaskBand {
1925 return _CreateMaskBand(@_);
1928 #** @method Geo::GDAL::Dataset DEMProcessing($Dest, $Processing, $ColorFilename, hashref Options, coderef progress, $progress_data)
1930 # Apply a DEM processing to this dataset.
1931 # @param Dest Destination raster dataset definition string (typically filename) or an object, which implements write and close.
1932 # @param Processing Processing to apply, one of "hillshade", "slope", "aspect", "color-relief", "TRI", "TPI", or "Roughness".
1933 # @param ColorFilename The color palette for color-relief.
1934 # @param Options See section \ref index_processing_options.
1935 # @param progress [optional] A reference to a subroutine, which will
1936 # be called with parameters (number progress, string msg, progress_data).
1937 # @param progress_data [optional]
1941 my ($self, $dest, $Processing, $ColorFilename, $options, $progress, $progress_data) = @_;
1942 $options = Geo::GDAL::GDALDEMProcessingOptions->new(make_processing_options($options));
1943 return $self->stdout_redirection_wrapper(
1945 \&Geo::GDAL::wrapper_GDALDEMProcessing,
1946 $Processing, $ColorFilename, $options, $progress, $progress_data
1950 #** @method Dataset()
1957 #** @method DeleteLayer($name)
1959 # Deletes a layer from the data source. Note that if there is a layer
1960 # object for the deleted layer, it becomes unusable.
1961 # @param name name of the layer to delete.
1964 my ($self, $name) = @_;
1966 for my $i (0..$self->GetLayerCount-1) {
1967 my $layer = GetLayerByIndex($self, $i);
1968 $index = $i, last if $layer->GetName eq $name;
1970 error(2, $name, 'Layer') unless defined $index;
1971 _DeleteLayer($self, $index);
1974 #** @method Geo::GDAL::Band Dither(%params)
1976 # Compute one band with color table image from an RGB image
1977 # @params params Named parameters:
1978 # - \a Red The red band, the default is to use the red band of this dataset.
1979 # - \a Green The green band, the default is to use the green band of this dataset.
1980 # - \a Blue The blue band, the default is to use the blue band of this dataset.
1981 # - \a Dest The destination band. If this is not defined, a new in-memory band (and a dataset) will be created.
1982 # - \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.
1983 # - \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.
1984 # - \a ProgressData (default is undef)
1986 # @return the destination band.
1988 # Usage example. This code converts an RGB JPEG image into a one band PNG image with a color table.
1990 # my $d = Geo::GDAL::Open('pic.jpg');
1991 # Geo::GDAL::Driver('PNG')->Copy(Name => 'test.png', Src => $d->Dither->Dataset);
1996 my $p = named_parameters(\@_,
2001 ColorTable => undef,
2003 ProgressData => undef);
2004 for my $b ($self->Bands) {
2005 for my $cion ($b->ColorInterpretation) {
2006 if ($cion eq 'RedBand') { $p->{red} //= $b; last; }
2007 if ($cion eq 'GreenBand') { $p->{green} //= $b; last; }
2008 if ($cion eq 'BlueBand') { $p->{blue} //= $b; last; }
2011 my ($w, $h) = $self->Size;
2012 $p->{dest} //= Geo::GDAL::Driver('MEM')->Create(Name => 'dithered',
2015 Type => 'Byte')->Band;
2017 //= $p->{dest}->ColorTable
2018 // $self->ComputeColorTable(Red => $p->{red},
2019 Green => $p->{green},
2021 Progress => $p->{progress},
2022 ProgressData => $p->{progressdata});
2023 Geo::GDAL::DitherRGB2PCT($p->{red},
2029 $p->{progressdata});
2030 $p->{dest}->ColorTable($p->{colortable});
2034 #** @method Domains()
2040 #** @method Geo::GDAL::Driver Driver()
2042 # @note a.k.a. GetDriver
2043 # @return a Geo::GDAL::Driver object that was used to open or create this dataset.
2048 #** @method Geo::OGR::Layer ExecuteSQL($statement, $geom = undef, $dialect = "")
2050 # @param statement A SQL statement.
2051 # @param geom A Geo::OGR::Geometry object.
2053 # @return a new Geo::OGR::Layer object. The data source object will
2054 # exist as long as the layer object exists.
2058 my $layer = $self->_ExecuteSQL(@_);
2059 note($layer, "is result set");
2060 keep($layer, $self);
2063 #** @method Geo::GDAL::Extent Extent(@params)
2065 # @param params nothing, or a list ($xoff, $yoff, $w, $h)
2066 # @return A new Geo::GDAL::Extent object that represents the area that
2067 # this raster or the specified tile covers.
2071 my $t = $self->GeoTransform;
2072 my $extent = $t->Extent($self->Size);
2074 my ($xoff, $yoff, $w, $h) = @_;
2075 my ($x, $y) = $t->Apply([$xoff, $xoff+$w, $xoff+$w, $xoff], [$yoff, $yoff, $yoff+$h, $yoff+$h]);
2076 my $xmin = shift @$x;
2079 $xmin = $x if $x < $xmin;
2080 $xmax = $x if $x > $xmax;
2082 my $ymin = shift @$y;
2085 $ymin = $y if $y < $ymin;
2086 $ymax = $y if $y > $ymax;
2088 $extent = Geo::GDAL::Extent->new($xmin, $ymin, $xmax, $ymax);
2093 #** @method list GCPs(@GCPs, Geo::OSR::SpatialReference sr)
2095 # Get or set the GCPs and their projection.
2096 # @param GCPs [optional] a list of Geo::GDAL::GCP objects
2097 # @param sr [optional] the projection of the GCPs.
2098 # @return a list of Geo::GDAL::GCP objects followed by a Geo::OSR::SpatialReference object.
2104 $proj = $proj->Export('WKT') if $proj and ref($proj);
2105 SetGCPs($self, \@_, $proj);
2107 return unless defined wantarray;
2108 my $proj = Geo::OSR::SpatialReference->new(GetGCPProjection($self));
2109 my $GCPs = GetGCPs($self);
2110 return (@$GCPs, $proj);
2113 #** @method Geo::GDAL::GeoTransform GeoTransform(Geo::GDAL::GeoTransform $geo_transform)
2115 # Transformation from cell coordinates (column,row) to projection
2118 # x = geo_transform[0] + column*geo_transform[1] + row*geo_transform[2]
2119 # y = geo_transform[3] + column*geo_transform[4] + row*geo_transform[5]
2121 # @param geo_transform [optional]
2122 # @return the geo transform in a non-void context.
2128 SetGeoTransform($self, $_[0]);
2130 SetGeoTransform($self, \@_);
2133 confess(last_error()) if $@;
2134 return unless defined wantarray;
2135 my $t = GetGeoTransform($self);
2139 return Geo::GDAL::GeoTransform->new($t);
2143 #** @method GetDriver()
2148 #** @method list GetFileList()
2150 # @return list of files GDAL believes to be part of this dataset.
2155 #** @method scalar GetGCPProjection()
2157 # @return projection string.
2159 sub GetGCPProjection {
2162 #** @method Geo::OGR::Layer GetLayer($name)
2164 # @param name the name of the requested layer. If not given, then
2165 # returns the first layer in the data source.
2166 # @return a new Geo::OGR::Layer object that represents the layer
2167 # in the data source.
2170 my($self, $name) = @_;
2171 my $layer = defined $name ? GetLayerByName($self, "$name") : GetLayerByIndex($self, 0);
2173 error(2, $name, 'Layer') unless $layer;
2174 keep($layer, $self);
2177 #** @method list GetLayerNames()
2179 # @note Delivers the functionality of undocumented method GetLayerCount.
2180 # @return a list of the names of the layers this data source provides.
2185 for my $i (0..$self->GetLayerCount-1) {
2186 my $layer = GetLayerByIndex($self, $i);
2187 push @names, $layer->GetName;
2192 #** @method GetNextFeature()
2194 sub GetNextFeature {
2197 #** @method GetStyleTable()
2202 #** @method Geo::GDAL::Dataset Grid($Dest, hashref Options)
2204 # Creates a regular raster grid from this data source.
2205 # This is equivalent to the gdal_grid utility.
2206 # @param Dest Destination raster dataset definition string (typically
2207 # filename) or an object, which implements write and close.
2208 # @param Options See section \ref index_processing_options.
2211 my ($self, $dest, $options, $progress, $progress_data) = @_;
2212 $options = Geo::GDAL::GDALGridOptions->new(make_processing_options($options));
2213 return $self->stdout_redirection_wrapper(
2215 \&Geo::GDAL::wrapper_GDALGrid,
2216 $options, $progress, $progress_data
2220 #** @method scalar Info(hashref Options)
2222 # Information about this dataset.
2223 # @param Options See section \ref index_processing_options.
2226 my ($self, $o) = @_;
2227 $o = Geo::GDAL::GDALInfoOptions->new(make_processing_options($o));
2228 return GDALInfo($self, $o);
2231 #** @method Geo::GDAL::Dataset Nearblack($Dest, hashref Options, coderef progress, $progress_data)
2233 # Convert nearly black/white pixels to black/white.
2234 # @param Dest Destination raster dataset definition string (typically
2235 # filename), destination dataset to which to add an alpha or mask
2236 # band, or an object, which implements write and close.
2237 # @param Options See section \ref index_processing_options.
2238 # @return Dataset if destination dataset definition string was given,
2239 # otherwise a boolean for success/fail but the method croaks if there
2243 my ($self, $dest, $options, $progress, $progress_data) = @_;
2244 $options = Geo::GDAL::GDALNearblackOptions->new(make_processing_options($options));
2245 my $b = blessed($dest);
2246 if ($b && $b eq 'Geo::GDAL::Dataset') {
2247 Geo::GDAL::wrapper_GDALNearblackDestDS($dest, $self, $options, $progress, $progress_data);
2249 return $self->stdout_redirection_wrapper(
2251 \&Geo::GDAL::wrapper_GDALNearblackDestName,
2252 $options, $progress, $progress_data
2257 #** @method Geo::GDAL::Dataset Open()
2258 # Package subroutine.
2259 # The same as Geo::GDAL::Open
2264 #** @method Geo::GDAL::Dataset OpenShared()
2265 # Package subroutine.
2266 # The same as Geo::GDAL::OpenShared
2271 #** @method Geo::GDAL::Dataset Rasterize($Dest, hashref Options, coderef progress, $progress_data)
2273 # Render data from this data source into a raster.
2274 # @param Dest Destination raster dataset definition string (typically
2275 # filename), destination dataset, or an object, which implements write and close.
2276 # @param Options See section \ref index_processing_options.
2277 # @return Dataset if destination dataset definition string was given,
2278 # otherwise a boolean for success/fail but the method croaks if there
2283 my ($self, $dest, $options, $progress, $progress_data) = @_;
2284 $options = Geo::GDAL::GDALRasterizeOptions->new(make_processing_options($options));
2285 my $b = blessed($dest);
2286 if ($b && $b eq 'Geo::GDAL::Dataset') {
2287 Geo::GDAL::wrapper_GDALRasterizeDestDS($dest, $self, $options, $progress, $progress_data);
2289 # TODO: options need to force a new raster be made, otherwise segfault
2290 return $self->stdout_redirection_wrapper(
2292 \&Geo::GDAL::wrapper_GDALRasterizeDestName,
2293 $options, $progress, $progress_data
2298 #** @method scalar ReadRaster(%params)
2300 # Read data from the dataset.
2302 # @param params Named parameters:
2303 # - \a XOff x offset (cell coordinates) (default is 0)
2304 # - \a YOff y offset (cell coordinates) (default is 0)
2305 # - \a XSize width of the area to read (default is the width of the dataset)
2306 # - \a YSize height of the area to read (default is the height of the dataset)
2307 # - \a BufXSize (default is undef, i.e., the same as XSize)
2308 # - \a BufYSize (default is undef, i.e., the same as YSize)
2309 # - \a BufType data type of the buffer (default is the data type of the first band)
2310 # - \a BandList a reference to an array of band indices (default is [1])
2311 # - \a BufPixelSpace (default is 0)
2312 # - \a BufLineSpace (default is 0)
2313 # - \a BufBandSpace (default is 0)
2314 # - \a ResampleAlg one of Geo::GDAL::RIOResamplingTypes (default is 'NearestNeighbour'),
2315 # - \a Progress reference to a progress function (default is undef)
2316 # - \a ProgressData (default is undef)
2318 # <a href="http://www.gdal.org/classGDALDataset.html">Entry in GDAL docs (method RasterIO)</a>
2319 # @return a buffer, open the buffer with \a unpack function of Perl. See Geo::GDAL::Band::PackCharacter.
2323 my ($width, $height) = $self->Size;
2324 my ($type) = $self->Band->DataType;
2325 my $p = named_parameters(\@_,
2337 ResampleAlg => 'NearestNeighbour',
2339 ProgressData => undef
2341 $p->{resamplealg} = s2i(rio_resampling => $p->{resamplealg});
2342 $p->{buftype} = s2i(data_type => $p->{buftype}, 1);
2343 $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});
2346 #** @method ReadTile()
2349 my ($self, $xoff, $yoff, $xsize, $ysize, $w_tile, $h_tile, $alg) = @_;
2351 for my $i (0..$self->Bands-1) {
2352 $data[$i] = $self->Band($i+1)->ReadTile($xoff, $yoff, $xsize, $ysize, $w_tile, $h_tile, $alg);
2357 #** @method ReleaseResultSet($layer)
2359 # @param layer A layer the has been created with ExecuteSQL.
2360 # @note There is no need to call this method. The result set layer is
2361 # released in the destructor of the layer that was created with SQL.
2363 sub ReleaseResultSet {
2364 # a no-op, _ReleaseResultSet is called from Layer::DESTROY
2367 #** @method ResetReading()
2372 #** @method RollbackTransaction()
2374 sub RollbackTransaction {
2377 #** @method SetStyleTable()
2382 #** @method list Size()
2384 # @return (width, height)
2388 return ($self->{RasterXSize}, $self->{RasterYSize});
2391 #** @method Geo::OSR::SpatialReference SpatialReference(Geo::OSR::SpatialReference sr)
2393 # Get or set the projection of this dataset.
2394 # @param sr [optional] a Geo::OSR::SpatialReference object,
2395 # which replaces the existing projection definition of this dataset.
2396 # @return a Geo::OSR::SpatialReference object, which represents the
2397 # projection of this dataset.
2398 # @note Methods GetProjection, SetProjection, and Projection return WKT strings.
2400 sub SpatialReference {
2401 my($self, $sr) = @_;
2402 SetProjection($self, $sr->As('WKT')) if defined $sr;
2403 if (defined wantarray) {
2404 my $p = GetProjection($self);
2406 return Geo::OSR::SpatialReference->new(WKT => $p);
2410 #** @method StartTransaction()
2412 sub StartTransaction {
2415 #** @method TestCapability()
2417 sub TestCapability {
2418 return _TestCapability(@_);
2421 #** @method Tile(Geo::GDAL::Extent e)
2423 # Compute the top left cell coordinates and width and height of the
2424 # tile that covers the given extent.
2425 # @param e The extent whose tile is needed.
2426 # @note Requires that the raster is a strictly north up one.
2427 # @return A list ($xoff, $yoff, $xsize, $ysize).
2430 my ($self, $e) = @_;
2431 my ($w, $h) = $self->Size;
2432 my $t = $self->GeoTransform;
2433 confess "GeoTransform is not \"north up\"." unless $t->NorthUp;
2434 my $xoff = floor(($e->[0] - $t->[0])/$t->[1]);
2435 $xoff = 0 if $xoff < 0;
2436 my $yoff = floor(($e->[1] - $t->[3])/$t->[5]);
2437 $yoff = 0 if $yoff < 0;
2438 my $xsize = ceil(($e->[2] - $t->[0])/$t->[1]) - $xoff;
2439 $xsize = $w - $xoff if $xsize > $w - $xoff;
2440 my $ysize = ceil(($e->[3] - $t->[3])/$t->[5]) - $yoff;
2441 $ysize = $h - $yoff if $ysize > $h - $yoff;
2442 return ($xoff, $yoff, $xsize, $ysize);
2445 #** @method Geo::GDAL::Dataset Translate($Dest, hashref Options, coderef progress, $progress_data)
2447 # Convert this dataset into another format.
2448 # @param Dest Destination dataset definition string (typically
2449 # filename) or an object, which implements write and close.
2450 # @param Options See section \ref index_processing_options.
2451 # @return New dataset object if destination dataset definition
2452 # string was given, otherwise a boolean for success/fail but the
2453 # method croaks if there was an error.
2456 my ($self, $dest, $options, $progress, $progress_data) = @_;
2457 return $self->stdout_redirection_wrapper(
2461 #** @method Geo::GDAL::Dataset Warp($Dest, hashref Options, coderef progress, $progress_data)
2463 # Reproject this dataset.
2464 # @param Dest Destination raster dataset definition string (typically
2465 # filename) or an object, which implements write and close.
2466 # @param Options See section \ref index_processing_options.
2467 # @note This method can be run as a package subroutine with a list of
2468 # datasets as the first argument to mosaic several datasets.
2471 my ($self, $dest, $options, $progress, $progress_data) = @_;
2472 # can be run as object method (one dataset) and as package sub (a list of datasets)
2473 $options = Geo::GDAL::GDALWarpAppOptions->new(make_processing_options($options));
2474 my $b = blessed($dest);
2475 $self = [$self] unless ref $self eq 'ARRAY';
2476 if ($b && $b eq 'Geo::GDAL::Dataset') {
2477 Geo::GDAL::wrapper_GDALWarpDestDS($dest, $self, $options, $progress, $progress_data);
2479 return stdout_redirection_wrapper(
2482 \&Geo::GDAL::wrapper_GDALWarpDestName,
2483 $options, $progress, $progress_data
2488 #** @method Geo::GDAL::Dataset Warped(%params)
2490 # Create a virtual warped dataset from this dataset.
2492 # @param params Named parameters:
2493 # - \a SrcSRS Override the spatial reference system of this dataset if there is one (default is undef).
2494 # - \a DstSRS The target spatial reference system of the result (default is undef).
2495 # - \a ResampleAlg The resampling algorithm (default is 'NearestNeighbour').
2496 # - \a MaxError Maximum error measured in input cellsize that is allowed in approximating the transformation (default is 0 for exact calculations).
2498 # # <a href="http://www.gdal.org/gdalwarper_8h.html">Documentation for GDAL warper.</a>
2500 # @return a new Geo::GDAL::Dataset object
2504 my $p = named_parameters(\@_, SrcSRS => undef, DstSRS => undef, ResampleAlg => 'NearestNeighbour', MaxError => 0);
2505 for my $srs (qw/srcsrs dstsrs/) {
2506 $p->{$srs} = $p->{$srs}->ExportToWkt if $p->{$srs} && blessed $p->{$srs};
2508 $p->{resamplealg} = s2i(resampling => $p->{resamplealg});
2509 my $warped = Geo::GDAL::_AutoCreateWarpedVRT($self, $p->{srcsrs}, $p->{dstsrs}, $p->{resamplealg}, $p->{maxerror});
2510 keep($warped, $self) if $warped; # self must live as long as warped
2513 #** @method WriteRaster(%params)
2515 # Write data into the dataset.
2517 # @param params Named parameters:
2518 # - \a XOff x offset (cell coordinates) (default is 0)
2519 # - \a YOff y offset (cell coordinates) (default is 0)
2520 # - \a XSize width of the area to write (default is the width of the dataset)
2521 # - \a YSize height of the area to write (default is the height of the dataset)
2522 # - \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.
2523 # - \a BufXSize (default is undef, i.e., the same as XSize)
2524 # - \a BufYSize (default is undef, i.e., the same as YSize)
2525 # - \a BufType data type of the buffer (default is the data type of the first band)
2526 # - \a BandList a reference to an array of band indices (default is [1])
2527 # - \a BufPixelSpace (default is 0)
2528 # - \a BufLineSpace (default is 0)
2529 # - \a BufBandSpace (default is 0)
2531 # <a href="http://www.gdal.org/classGDALDataset.html">Entry in GDAL docs (method RasterIO)</a>
2535 my ($width, $height) = $self->Size;
2536 my ($type) = $self->Band->DataType;
2537 my $p = named_parameters(\@_,
2551 $p->{buftype} = s2i(data_type => $p->{buftype}, 1);
2552 $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});
2555 #** @method WriteTile()
2558 my ($self, $data, $xoff, $yoff) = @_;
2561 for my $i (0..$self->Bands-1) {
2562 $self->Band($i+1)->WriteTile($data->[$i], $xoff, $yoff);
2566 #** @class Geo::GDAL::Driver
2567 # @brief A driver for a specific dataset format.
2570 package Geo::GDAL::Driver;
2572 use base qw(Geo::GDAL::MajorObject Geo::GDAL)
2574 #** @attr $HelpTopic
2575 # $driver->{HelpTopic}
2579 # $driver->{LongName}
2582 #** @attr $ShortName
2583 # $driver->{ShortName}
2586 #** @method list Capabilities()
2588 # @return A list of capabilities. When executed as a package subroutine
2589 # returns a list of all potential capabilities a driver may have. When
2590 # executed as an object method returns a list of all capabilities the
2593 # Currently capabilities are:
2594 # CREATE, CREATECOPY, DEFAULT_FIELDS, NOTNULL_FIELDS, NOTNULL_GEOMFIELDS, OPEN, RASTER, VECTOR, and VIRTUALIO.
2598 # @all_capabilities = Geo::GDAL::Driver::Capabilities;
2599 # @capabilities_of_the_geotiff_driver = Geo::GDAL::Driver('GTiff')->Capabilities;
2604 return @CAPABILITIES unless $self;
2605 my $h = $self->GetMetadata;
2607 for my $cap (@CAPABILITIES) {
2608 my $test = $h->{'DCAP_'.uc($cap)};
2609 push @cap, $cap if defined($test) and $test eq 'YES';
2614 #** @method Geo::GDAL::Dataset Copy(%params)
2616 # Create a new raster Geo::GDAL::Dataset as a copy of an existing dataset.
2617 # @note a.k.a. CreateCopy
2619 # @param params Named parameters:
2620 # - \a Name name for the new raster dataset.
2621 # - \a Src the source Geo::GDAL::Dataset object.
2622 # - \a Strict 1 (default) if the copy must be strictly equivalent, or 0 if the copy may adapt.
2623 # - \a Options an anonymous hash of driver specific options.
2624 # - \a Progress [optional] a reference to a subroutine, which will
2625 # be called with parameters (number progress, string msg, progress_data).
2626 # - \a ProgressData [optional]
2627 # @return a new Geo::GDAL::Dataset object.
2631 my $p = named_parameters(\@_, Name => 'unnamed', Src => undef, Strict => 1, Options => {}, Progress => undef, ProgressData => undef);
2632 return $self->stdout_redirection_wrapper(
2634 $self->can('_CreateCopy'),
2635 $p->{src}, $p->{strict}, $p->{options}, $p->{progress}, $p->{progressdata});
2638 #** @method CopyFiles($NewName, $OldName)
2640 # Copy the files of a dataset.
2641 # @param NewName String.
2642 # @param OldName String.
2647 #** @method Geo::GDAL::Dataset Create(%params)
2649 # Create a raster dataset using this driver.
2650 # @note a.k.a. CreateDataset
2652 # @param params Named parameters:
2653 # - \a Name The name for the dataset (default is 'unnamed') or an object, which implements write and close.
2654 # - \a Width The width for the raster dataset (default is 256).
2655 # - \a Height The height for the raster dataset (default is 256).
2656 # - \a Bands The number of bands to create into the raster dataset (default is 1).
2657 # - \a Type The data type for the raster cells (default is 'Byte'). One of Geo::GDAL::Driver::CreationDataTypes.
2658 # - \a Options Driver creation options as a reference to a hash (default is {}).
2660 # @return A new Geo::GDAL::Dataset object.
2664 my $p = named_parameters(\@_, Name => 'unnamed', Width => 256, Height => 256, Bands => 1, Type => 'Byte', Options => {});
2665 my $type = s2i(data_type => $p->{type});
2666 return $self->stdout_redirection_wrapper(
2668 $self->can('_Create'),
2669 $p->{width}, $p->{height}, $p->{bands}, $type, $p->{options}
2673 #** @method list CreationDataTypes()
2675 # @return a list of data types that can be used for new datasets of this format. A subset of Geo::GDAL::DataTypes
2677 sub CreationDataTypes {
2679 my $h = $self->GetMetadata;
2680 return split /\s+/, $h->{DMD_CREATIONDATATYPES} if $h->{DMD_CREATIONDATATYPES};
2683 #** @method list CreationOptionList()
2685 # @return a list of options, each option is a hashref, the keys are
2686 # name, type and description or Value. Value is a listref.
2688 sub CreationOptionList {
2691 my $h = $self->GetMetadata->{DMD_CREATIONOPTIONLIST};
2693 $h = ParseXMLString($h);
2694 my($type, $value) = NodeData($h);
2695 if ($value eq 'CreationOptionList') {
2696 for my $o (Children($h)) {
2698 for my $a (Children($o)) {
2699 my(undef, $key) = NodeData($a);
2700 my(undef, $value) = NodeData(Child($a, 0));
2701 if ($key eq 'Value') {
2702 push @{$option{$key}}, $value;
2704 $option{$key} = $value;
2707 push @options, \%option;
2714 #** @method Delete($name)
2721 #** @method Domains()
2727 #** @method scalar Extension()
2729 # @note The returned extension does not contain a '.' prefix.
2730 # @return a suggested single extension or a list of extensions (in
2731 # list context) for datasets.
2735 my $h = $self->GetMetadata;
2737 my $e = $h->{DMD_EXTENSIONS};
2738 my @e = split / /, $e;
2739 @e = split /\//, $e if $e =~ /\//; # ILWIS returns mpr/mpl
2740 for my $i (0..$#e) {
2741 $e[$i] =~ s/^\.//; # CALS returns extensions with a dot prefix
2745 my $e = $h->{DMD_EXTENSION};
2746 return '' if $e =~ /\//; # ILWIS returns mpr/mpl
2752 #** @method scalar MIMEType()
2754 # @return a suggested MIME type for datasets.
2758 my $h = $self->GetMetadata;
2759 return $h->{DMD_MIMETYPE};
2762 #** @method scalar Name()
2764 # @return The short name of the driver.
2768 return $self->{ShortName};
2773 # The same as Geo::GDAL::Open except that only this driver is allowed.
2777 my @p = @_; # name, update
2778 my @flags = qw/RASTER/;
2779 push @flags, qw/READONLY/ if $p[1] eq 'ReadOnly';
2780 push @flags, qw/UPDATE/ if $p[1] eq 'Update';
2781 my $dataset = OpenEx($p[0], \@flags, [$self->Name()]);
2782 error("Failed to open $p[0]. Is it a raster dataset?") unless $dataset;
2786 #** @method Rename($NewName, $OldName)
2788 # Rename (move) a GDAL dataset.
2789 # @param NewName String.
2790 # @param OldName String.
2795 #** @method scalar TestCapability($cap)
2797 # Test whether the driver has the specified capability.
2798 # @param cap A capability string (one of those returned by Capabilities).
2799 # @return a boolean value.
2801 sub TestCapability {
2802 my($self, $cap) = @_;
2803 my $h = $self->GetMetadata->{'DCAP_'.uc($cap)};
2804 return (defined($h) and $h eq 'YES') ? 1 : undef;
2807 #** @method stdout_redirection_wrapper()
2809 sub stdout_redirection_wrapper {
2810 my ($self, $name, $sub, @params) = @_;
2812 if ($name && blessed $name) {
2814 my $ref = $object->can('write');
2815 VSIStdoutSetRedirection($ref);
2816 $name = '/vsistdout/';
2820 $ds = $sub->($self, $name, @params);
2824 $Geo::GDAL::stdout_redirection{tied(%$ds)} = $object;
2826 VSIStdoutUnsetRedirection();
2830 confess(last_error()) if $@;
2831 confess("Failed. Use Geo::OGR::Driver for vector drivers.") unless $ds;
2835 #** @class Geo::GDAL::Extent
2836 # @brief A rectangular area in projection coordinates: xmin, ymin, xmax, ymax.
2838 package Geo::GDAL::Extent;
2840 #** @method ExpandToInclude($extent)
2841 # Package subroutine.
2842 # Extends this extent to include the other extent.
2843 # @param extent Another Geo::GDAL::Extent object.
2845 sub ExpandToInclude {
2846 my ($self, $e) = @_;
2847 return if $e->IsEmpty;
2848 if ($self->IsEmpty) {
2851 $self->[0] = $e->[0] if $e->[0] < $self->[0];
2852 $self->[1] = $e->[1] if $e->[1] < $self->[1];
2853 $self->[2] = $e->[2] if $e->[2] > $self->[2];
2854 $self->[3] = $e->[3] if $e->[3] > $self->[3];
2858 #** @method IsEmpty()
2862 return $self->[2] < $self->[0];
2865 #** @method scalar Overlap($extent)
2866 # Package subroutine.
2867 # @param extent Another Geo::GDAL::Extent object.
2868 # @return A new, possibly empty, Geo::GDAL::Extent object, which
2869 # represents the joint area of the two extents.
2872 my ($self, $e) = @_;
2873 return Geo::GDAL::Extent->new() unless $self->Overlaps($e);
2874 my $ret = Geo::GDAL::Extent->new($self);
2875 $ret->[0] = $e->[0] if $self->[0] < $e->[0];
2876 $ret->[1] = $e->[1] if $self->[1] < $e->[1];
2877 $ret->[2] = $e->[2] if $self->[2] > $e->[2];
2878 $ret->[3] = $e->[3] if $self->[3] > $e->[3];
2882 #** @method scalar Overlaps($extent)
2883 # Package subroutine.
2884 # @param extent Another Geo::GDAL::Extent object.
2885 # @return True if this extent overlaps the other extent, false otherwise.
2888 my ($self, $e) = @_;
2889 return $self->[0] < $e->[2] && $self->[2] > $e->[0] && $self->[1] < $e->[3] && $self->[3] > $e->[1];
2892 #** @method list Size()
2893 # Package subroutine.
2894 # @return A list ($width, $height).
2898 return (0,0) if $self->IsEmpty;
2899 return ($self->[2] - $self->[0], $self->[3] - $self->[1]);
2902 #** @method Geo::GDAL::Extent new(@params)
2903 # Package subroutine.
2904 # @param params nothing, a list ($xmin, $ymin, $xmax, $ymax), or an Extent object
2905 # @return A new Extent object (empty if no parameters, a copy of the parameter if it is an Extent object).
2912 } elsif (ref $_[0]) {
2917 bless $self, $class;
2921 #** @class Geo::GDAL::GCP
2922 # @brief A ground control point for georeferencing rasters.
2925 package Geo::GDAL::GCP;
2927 use base qw(Geo::GDAL)
2930 # cell x coordinate (access as $gcp->{Column})
2934 # unique identifier (string) (access as $gcp->{Id})
2938 # informational message (access as $gcp->{Info})
2942 # cell y coordinate (access as $gcp->{Row})
2946 # projection coordinate (access as $gcp->{X})
2950 # projection coordinate (access as $gcp->{Y})
2954 # projection coordinate (access as $gcp->{Z})
2957 #** @method scalar new($x = 0.0, $y = 0.0, $z = 0.0, $column = 0.0, $row = 0.0, $info = "", $id = "")
2959 # @param x projection coordinate
2960 # @param y projection coordinate
2961 # @param z projection coordinate
2962 # @param column cell x coordinate
2963 # @param row cell y coordinate
2964 # @param info informational message
2965 # @param id unique identifier (string)
2966 # @return a new Geo::GDAL::GCP object
2970 my $self = Geo::GDALc::new_GCP(@_);
2971 bless $self, $pkg if defined($self);
2974 #** @class Geo::GDAL::GeoTransform
2975 # @brief An array of affine transformation coefficients.
2976 # @details The geo transformation has the form
2978 # x = a + column * b + row * c
2979 # y = d + column * e + row * f
2982 # (column,row) is the location in cell coordinates, and
2983 # (x,y) is the location in projection coordinates, or vice versa.
2984 # A Geo::GDAL::GeoTransform object is a reference to an anonymous array [a,b,c,d,e,f].
2986 package Geo::GDAL::GeoTransform;
2988 #** @method Apply($x, $y)
2990 # @param x Column or x, or a reference to an array of columns or x's
2991 # @param y Row or y, or a reference to an array of rows or y's
2992 # @return a list (x, y), where x and y are the transformed coordinates
2993 # or references to arrays of transformed coordinates.
2996 my ($self, $columns, $rows) = @_;
2997 return Geo::GDAL::ApplyGeoTransform($self, $columns, $rows) unless ref($columns) eq 'ARRAY';
2999 for my $i (0..$#$columns) {
3001 Geo::GDAL::ApplyGeoTransform($self, $columns->[$i], $rows->[$i]);
3008 # @return a new Geo::GDAL::GeoTransform object, which is the inverse
3009 # of this one (in void context changes this object).
3013 my @inv = Geo::GDAL::InvGeoTransform($self);
3014 return Geo::GDAL::GeoTransform->new(@inv) if defined wantarray;
3018 #** @method NorthUp()
3022 return $self->[2] == 0 && $self->[4] == 0;
3025 #** @method new(@params)
3027 # @param params nothing, a reference to an array [a,b,c,d,e,f], a list
3028 # (a,b,c,d,e,f), or named parameters
3029 # - \a GCPs A reference to an array of Geo::GDAL::GCP objects.
3030 # - \a ApproxOK Minimize the error in the coefficients (integer, default is 1 (true), used with GCPs).
3031 # - \a Extent A Geo::GDAL::Extent object used to obtain the coordinates of the up left corner position.
3032 # - \a CellSize The cell size (width and height) (default is 1, used with Extent).
3034 # @note When Extent is specifid, the created geo transform will be
3035 # north up, have square cells, and coefficient f will be -1 times the
3036 # cell size (image y - row - will increase downwards and projection y
3037 # will increase upwards).
3038 # @return a new Geo::GDAL::GeoTransform object.
3044 $self = [0,1,0,0,0,1];
3045 } elsif (ref $_[0]) {
3047 } elsif ($_[0] =~ /^[a-zA-Z]/i) {
3048 my $p = named_parameters(\@_, GCPs => undef, ApproxOK => 1, Extent => undef, CellSize => 1);
3050 $self = Geo::GDAL::GCPsToGeoTransform($p->{gcps}, $p->{approxok});
3051 } elsif ($p->{extent}) {
3052 $self = Geo::GDAL::GeoTransform->new($p->{extent}[0], $p->{cellsize}, 0, $p->{extent}[2], 0, -$p->{cellsize});
3054 error("Missing GCPs or Extent");
3060 bless $self, $class;
3063 #** @class Geo::GDAL::MajorObject
3064 # @brief An object, which holds meta data.
3067 package Geo::GDAL::MajorObject;
3069 use base qw(Geo::GDAL)
3071 #** @method scalar Description($description)
3073 # @param description [optional]
3074 # @return the description in a non-void context.
3077 my($self, $desc) = @_;
3078 SetDescription($self, $desc) if defined $desc;
3079 GetDescription($self) if defined wantarray;
3082 #** @method Domains()
3083 # Package subroutine.
3084 # @return the class specific DOMAINS list
3090 #** @method scalar GetDescription()
3094 sub GetDescription {
3097 #** @method hash reference GetMetadata($domain = "")
3099 # @note see Metadata
3106 #** @method GetMetadataDomainList()
3108 sub GetMetadataDomainList {
3111 #** @method hash reference Metadata(hashref metadata = undef, $domain = '')
3115 # @return the metadata in a non-void context.
3119 my $metadata = ref $_[0] ? shift : undef;
3120 my $domain = shift // '';
3121 SetMetadata($self, $metadata, $domain) if defined $metadata;
3122 GetMetadata($self, $domain) if defined wantarray;
3125 #** @method SetDescription($NewDesc)
3130 sub SetDescription {
3133 #** @method SetMetadata(hashref metadata, $domain = "")
3135 # @note see Metadata
3143 #** @class Geo::GDAL::RasterAttributeTable
3144 # @brief An attribute table in a raster band.
3147 package Geo::GDAL::RasterAttributeTable;
3149 use base qw(Geo::GDAL)
3158 #** @method ChangesAreWrittenToFile()
3160 sub ChangesAreWrittenToFile {
3163 #** @method Geo::GDAL::RasterAttributeTable Clone()
3165 # @return a new Geo::GDAL::RasterAttributeTable object
3170 #** @method hash Columns(%columns)
3172 # A get/set method for the columns of the RAT
3173 # @param columns optional, a the keys are column names and the values are anonymous
3174 # hashes with keys Type and Usage
3175 # @return a hash similar to the optional input parameter
3180 if (@_) { # create columns
3182 for my $name (keys %columns) {
3183 $self->CreateColumn($name, $columns{$name}{Type}, $columns{$name}{Usage});
3187 for my $c (0..$self->GetColumnCount-1) {
3188 my $name = $self->GetNameOfCol($c);
3189 $columns{$name}{Type} = $self->GetTypeOfCol($c);
3190 $columns{$name}{Usage} = $self->GetUsageOfCol($c);
3195 #** @method CreateColumn($name, $type, $usage)
3198 # @param type one of FieldTypes
3199 # @param usage one of FieldUsages
3202 my($self, $name, $type, $usage) = @_;
3203 for my $color (qw/Red Green Blue Alpha/) {
3204 carp "RAT column type will be 'Integer' for usage '$color'." if $usage eq $color and $type ne 'Integer';
3206 $type = s2i(rat_field_type => $type);
3207 $usage = s2i(rat_field_usage => $usage);
3208 _CreateColumn($self, $name, $type, $usage);
3211 #** @method DumpReadable()
3216 #** @method list FieldTypes()
3217 # Package subroutine.
3221 return @FIELD_TYPES;
3224 #** @method list FieldUsages()
3225 # Package subroutine.
3229 return @FIELD_USAGES;
3232 #** @method scalar GetColOfUsage($usage)
3238 my($self, $usage) = @_;
3239 _GetColOfUsage($self, s2i(rat_field_usage => $usage));
3242 #** @method scalar GetColumnCount()
3246 sub GetColumnCount {
3249 #** @method scalar GetNameOfCol($column)
3257 #** @method scalar GetRowCount()
3263 #** @method scalar GetRowOfValue($value)
3265 # @param value a cell value
3266 # @return row index or -1
3271 #** @method scalar GetTypeOfCol($column)
3277 my($self, $col) = @_;
3278 i2s(rat_field_type => _GetTypeOfCol($self, $col));
3281 #** @method scalar GetUsageOfCol($column)
3287 my($self, $col) = @_;
3288 i2s(rat_field_usage => _GetUsageOfCol($self, $col));
3291 #** @method scalar GetValueAsDouble($row, $column)
3297 sub GetValueAsDouble {
3300 #** @method scalar GetValueAsInt($row, $column)
3309 #** @method scalar GetValueAsString($row, $column)
3315 sub GetValueAsString {
3318 #** @method LinearBinning($Row0MinIn, $BinSizeIn)
3320 # @param Row0MinIn [optional] the lower bound (cell value) of the first category.
3321 # @param BinSizeIn [optional] the width of each category (in cell value units).
3322 # @return ($Row0MinIn, $BinSizeIn) or an empty list if LinearBinning is not set.
3326 SetLinearBinning($self, @_) if @_ > 0;
3327 return unless defined wantarray;
3328 my @a = GetLinearBinning($self);
3329 return $a[0] ? ($a[1], $a[2]) : ();
3332 #** @method SetRowCount($count)
3340 #** @method SetValueAsDouble($row, $column, $value)
3347 sub SetValueAsDouble {
3350 #** @method SetValueAsInt($row, $column, $value)
3360 #** @method SetValueAsString($row, $column, $value)
3367 sub SetValueAsString {
3370 #** @method scalar Value($row, $column, $value)
3374 # @param value [optional]
3378 my($self, $row, $column) = @_;
3379 SetValueAsString($self, $row, $column, $_[3]) if defined $_[3];
3380 return unless defined wantarray;
3381 GetValueAsString($self, $row, $column);
3384 #** @method Geo::GDAL::RasterAttributeTable new()
3386 # @return a new Geo::GDAL::RasterAttributeTable object
3390 my $self = Geo::GDALc::new_RasterAttributeTable(@_);
3391 bless $self, $pkg if defined($self);
3394 #** @class Geo::GDAL::Transformer
3396 # @details This class is not yet documented for the GDAL Perl bindings.
3397 # @todo Test and document.
3399 package Geo::GDAL::Transformer;
3401 use base qw(Geo::GDAL)
3403 #** @method TransformGeolocations()
3405 sub TransformGeolocations {
3408 #** @method TransformPoint()
3410 sub TransformPoint {
3417 my $self = Geo::GDALc::new_Transformer(@_);
3418 bless $self, $pkg if defined($self);
3421 #** @class Geo::GDAL::VSIF
3422 # @brief A GDAL virtual file system.
3425 package Geo::GDAL::VSIF;
3427 use base qw(Exporter)
3434 Geo::GDAL::VSIFCloseL($self);
3437 #** @method MkDir($path)
3438 # Package subroutine.
3440 # @param path The directory to make.
3441 # @note The name of this method is VSIMkdir in GDAL.
3445 # mode unused in CPL
3446 Geo::GDAL::Mkdir($path, 0);
3449 #** @method Geo::GDAL::VSIF Open($filename, $mode)
3450 # Package subroutine.
3451 # @param filename Name of the file to open. For example "/vsimem/x".
3452 # @param mode Access mode. 'r', 'r+', 'w', etc.
3453 # @return A file handle on success.
3456 my ($path, $mode) = @_;
3457 my $self = Geo::GDAL::VSIFOpenL($path, $mode);
3458 bless $self, 'Geo::GDAL::VSIF';
3461 #** @method scalar Read($count)
3463 # @param count The number of bytes to read from the file.
3464 # @return A byte string.
3467 my ($self, $count) = @_;
3468 Geo::GDAL::VSIFReadL($count, $self);
3471 #** @method list ReadDir($dir)
3472 # Package subroutine.
3473 # @return Contents of a directory in an anonymous array or as a list.
3477 Geo::GDAL::ReadDir($path);
3480 #** @method scalar ReadDirRecursive($dir)
3481 # Package subroutine.
3482 # @note Give the directory in the form '/vsimem', i.e., without trailing '/'.
3483 # @return Contents of a directory tree in an anonymous array.
3485 sub ReadDirRecursive {
3487 Geo::GDAL::ReadDirRecursive($path);
3490 #** @method Rename($old, $new)
3491 # Package subroutine.
3493 # @note The name of this method is VSIRename in GDAL.
3496 my ($old, $new) = @_;
3497 Geo::GDAL::Rename($old, $new);
3500 #** @method RmDir($path)
3501 # Package subroutine.
3502 # Remove a directory.
3503 # @note The name of this method is VSIRmdir in GDAL.
3506 my ($dirname, $recursive) = @_;
3509 Geo::GDAL::Rmdir($dirname);
3511 for my $f (ReadDir($dirname)) {
3512 next if $f eq '..' or $f eq '.';
3513 my @s = Stat($dirname.'/'.$f);
3515 Unlink($dirname.'/'.$f);
3516 } elsif ($s[0] eq 'd') {
3517 Rmdir($dirname.'/'.$f, 1);
3518 Rmdir($dirname.'/'.$f);
3525 my $r = $recursive ? ' recursively' : '';
3526 error("Cannot remove directory \"$dirname\"$r.");
3530 #** @method Seek($offset, $whence)
3534 my ($self, $offset, $whence) = @_;
3535 Geo::GDAL::VSIFSeekL($self, $offset, $whence);
3538 #** @method list Stat($filename)
3539 # Package subroutine.
3540 # @return ($filemode, $filesize). filemode is f for a plain file, d
3541 # for a directory, l for a symbolic link, p for a named pipe (FIFO), S
3542 # for a socket, b for a block special file, and c for a character
3547 Geo::GDAL::Stat($path);
3550 #** @method scalar Tell()
3555 Geo::GDAL::VSIFTellL($self);
3558 #** @method Truncate($new_size)
3562 my ($self, $new_size) = @_;
3563 Geo::GDAL::VSIFTruncateL($self, $new_size);
3566 #** @method Unlink($filename)
3567 # Package subroutine.
3568 # @param filename The file to delete.
3569 # @return 0 on success and -1 on an error.
3572 my ($filename) = @_;
3573 Geo::GDAL::Unlink($filename);
3576 #** @method Write($scalar)
3578 # @param scalar The byte string to write to the file.
3579 # @return Number of bytes written into the file.
3582 my ($self, $data) = @_;
3583 Geo::GDAL::VSIFWriteL($data, $self);
3586 #** @class Geo::GDAL::VSILFILE
3588 package Geo::GDAL::VSILFILE;
3590 use base qw(Geo::GDAL)
3592 #** @class Geo::GDAL::XML
3593 # @brief A simple XML parser
3596 package Geo::GDAL::XML;
3598 #** @method new($string)
3600 # @param string String containing XML.
3601 # @return A new Geo::GDAL::XML object, which is a reference to an anonymous array.
3605 my $xml = shift // '';
3606 my $self = ParseXMLString($xml);
3607 bless $self, $class;
3608 $self->traverse(sub {my $node = shift; bless $node, $class});
3612 #** @method serialize()
3614 # @return The XML serialized into a string.
3618 return SerializeXMLTree($self);
3621 # This file was automatically generated by SWIG (http://www.swig.org).
3624 # Do not make changes to this file unless you know what you are doing--modify
3625 # the SWIG interface file instead.
3628 #** @method traverse(coderef subroutine)
3630 # @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.
3633 my ($self, $sub) = @_;
3634 my $type = $self->[0];
3635 my $data = $self->[1];
3636 $type = NodeType($type);
3637 $sub->($self, $type, $data);
3638 for my $child (@{$self}[2..$#$self]) {
3639 traverse($child, $sub);
3644 # @brief Base class for geographical networks in GDAL.
3649 #** @method CastToGenericNetwork()
3651 sub CastToGenericNetwork {
3654 #** @method CastToNetwork()
3659 #** @method GATConnectedComponents()
3661 sub GATConnectedComponents {
3664 #** @method GATDijkstraShortestPath()
3666 sub GATDijkstraShortestPath {
3669 #** @method GATKShortestPath()
3671 sub GATKShortestPath {
3674 #** @method GNM_EDGE_DIR_BOTH()
3676 sub GNM_EDGE_DIR_BOTH {
3679 #** @method GNM_EDGE_DIR_SRCTOTGT()
3681 sub GNM_EDGE_DIR_SRCTOTGT {
3684 #** @method GNM_EDGE_DIR_TGTTOSRC()
3686 sub GNM_EDGE_DIR_TGTTOSRC {
3690 #** @class Geo::GNM::GenericNetwork
3693 package Geo::GNM::GenericNetwork;
3695 use base qw(Geo::GNM::Network Geo::GNM)
3697 #** @method ChangeAllBlockState()
3699 sub ChangeAllBlockState {
3702 #** @method ChangeBlockState()
3704 sub ChangeBlockState {
3707 #** @method ConnectFeatures()
3709 sub ConnectFeatures {
3712 #** @method ConnectPointsByLines()
3714 sub ConnectPointsByLines {
3717 #** @method CreateRule()
3722 #** @method DeleteAllRules()
3724 sub DeleteAllRules {
3727 #** @method DeleteRule()
3732 #** @method DisconnectFeatures()
3734 sub DisconnectFeatures {
3737 #** @method DisconnectFeaturesWithId()
3739 sub DisconnectFeaturesWithId {
3742 #** @method GetRules()
3747 #** @method ReconnectFeatures()
3749 sub ReconnectFeatures {
3752 #** @class Geo::GNM::MajorObject
3755 package Geo::GNM::MajorObject;
3757 #** @class Geo::GNM::Network
3760 package Geo::GNM::Network;
3762 use base qw(Geo::GDAL::MajorObject Geo::GNM)
3764 #** @method CommitTransaction()
3766 sub CommitTransaction {
3769 #** @method CopyLayer()
3774 #** @method DisconnectAll()
3779 #** @method GetFeatureByGlobalFID()
3781 sub GetFeatureByGlobalFID {
3784 #** @method GetFileList()
3789 #** @method GetLayerByIndex()
3791 sub GetLayerByIndex {
3794 #** @method GetLayerByName()
3796 sub GetLayerByName {
3799 #** @method GetLayerCount()
3804 #** @method GetName()
3809 #** @method GetPath()
3814 #** @method GetProjection()
3819 #** @method GetProjectionRef()
3821 sub GetProjectionRef {
3824 #** @method GetVersion()
3829 #** @method RollbackTransaction()
3831 sub RollbackTransaction {
3834 #** @method StartTransaction()
3836 sub StartTransaction {
3840 # @brief OGR utility functions.
3841 # @details A wrapper for many OGR utility functions and a root class for all
3846 #** @method list ByteOrders()
3847 # Package subroutine.
3848 # @return a list of byte order types, XDR and NDR. XDR denotes
3849 # big-endian and NDR denotes little-endian.
3854 #** @method Geo::GDAL::Driver Driver($name)
3855 # Package subroutine.
3857 # @param name the short name of the driver.
3858 # @note No check is made that the driver is actually a vector driver.
3859 # @return a Geo::GDAL::Driver object.
3862 return 'Geo::GDAL::Driver' unless @_;
3863 bless Geo::GDAL::Driver(@_), 'Geo::OGR::Driver';
3866 #** @method list DriverNames()
3867 # Package subroutine.
3868 # A.k.a GetDriverNames
3870 # perl -MGeo::GDAL -e '@d=Geo::OGR::DriverNames;print "@d\n"'
3872 # @note Use Geo::GDAL::DriverNames for raster drivers.
3873 # @return a list of the short names of all available GDAL vector drivers.
3878 #** @method list Drivers()
3879 # Package subroutine.
3880 # @note Use Geo::GDAL::Drivers for raster drivers.
3881 # @return a list of all available GDAL vector drivers.
3885 for my $i (0..GetDriverCount()-1) {
3886 my $driver = Geo::GDAL::GetDriver($i);
3887 push @drivers, $driver if $driver->TestCapability('VECTOR');
3892 #** @method Flatten()
3897 #** @method scalar GeometryTypeModify($type, $modifier)
3899 # @param type a geometry type (one of Geo::OGR::GeometryTypes).
3900 # @param modifier one of 'flatten', 'set_Z', 'make_collection', 'make_curve', or 'make_linear'.
3901 # @return modified geometry type.
3903 sub GeometryTypeModify {
3904 my($type, $modifier) = @_;
3905 $type = s2i(geometry_type => $type);
3906 return i2s(geometry_type => GT_Flatten($type)) if $modifier =~ /flat/i;
3907 return i2s(geometry_type => GT_SetZ($type)) if $modifier =~ /z/i;
3908 return i2s(geometry_type => GT_GetCollection($type)) if $modifier =~ /collection/i;
3909 return i2s(geometry_type => GT_GetCurve($type)) if $modifier =~ /curve/i;
3910 return i2s(geometry_type => GT_GetLinear($type)) if $modifier =~ /linear/i;
3911 error(1, $modifier, {Flatten => 1, SetZ => 1, GetCollection => 1, GetCurve => 1, GetLinear => 1});
3914 #** @method scalar GeometryTypeTest($type, $test, $type2)
3916 # @param type a geometry type (one of Geo::OGR::GeometryTypes).
3917 # @param test one of 'has_z', 'is_subclass_of', 'is_curve', 'is_surface', or 'is_non_linear'.
3918 # @param type2 a geometry type (one of Geo::OGR::GeometryTypes). Required for 'is_subclass_of' test.
3919 # @return result of the test.
3921 sub GeometryTypeTest {
3922 my($type, $test, $type2) = @_;
3923 $type = s2i(geometry_type => $type);
3924 if (defined $type2) {
3925 $type = s2i(geometry_type => $type);
3927 error("Usage: GeometryTypeTest(type1, 'is_subclass_of', type2).") if $test =~ /subclass/i;
3929 return GT_HasZ($type) if $test =~ /z/i;
3930 return GT_IsSubClassOf($type, $type2) if $test =~ /subclass/i;
3931 return GT_IsCurve($type) if $test =~ /curve/i;
3932 return GT_IsSurface($type) if $test =~ /surface/i;
3933 return GT_IsNonLinear($type) if $test =~ /linear/i;
3934 error(1, $test, {HasZ => 1, IsSubClassOf => 1, IsCurve => 1, IsSurface => 1, IsNonLinear => 1});
3937 #** @method list GeometryTypes()
3938 # Package subroutine.
3939 # @return a list of all geometry types, currently:
3940 # 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.
3944 # This file was automatically generated by SWIG (http://www.swig.org).
3947 # Do not make changes to this file unless you know what you are doing--modify
3948 # the SWIG interface file instead.
3951 #** @method GetNonLinearGeometriesEnabledFlag()
3953 sub GetNonLinearGeometriesEnabledFlag {
3956 #** @method GetOpenDSCount()
3958 sub GetOpenDSCount {
3971 #** @method Geo::GDAL::Dataset Open($name, $update = 0)
3973 # Open a vector data source.
3974 # @param name The data source string (directory, filename, etc.).
3975 # @param update Whether to open the data source in update mode (default is not).
3976 # @return a new Geo::GDAL::Dataset object.
3979 my @p = @_; # name, update
3980 my @flags = qw/VECTOR/;
3981 push @flags, qw/UPDATE/ if $p[1];
3982 my $dataset = Geo::GDAL::OpenEx($p[0], \@flags);
3983 error("Failed to open $p[0]. Is it a vector dataset?") unless $dataset;
3987 #** @method Geo::GDAL::Dataset OpenShared($name, $update = 0)
3989 # Open a vector data source in shared mode.
3990 # @param name The data source string (directory, filename, etc.).
3991 # @param update Whether to open the data source in update mode.
3992 # @return a new Geo::GDAL::Dataset object.
3995 my @p = @_; # name, update
3996 my @flags = qw/VECTOR SHARED/;
3997 push @flags, qw/UPDATE/ if $p[1];
3998 my $dataset = Geo::GDAL::OpenEx($p[0], \@flags);
3999 error("Failed to open $p[0]. Is it a vector dataset?") unless $dataset;
4003 #** @method SetGenerate_DB2_V72_BYTE_ORDER($Generate_DB2_V72_BYTE_ORDER)
4005 # Needed only on IBM DB2.
4007 sub SetGenerate_DB2_V72_BYTE_ORDER {
4010 #** @method SetNonLinearGeometriesEnabledFlag()
4012 sub SetNonLinearGeometriesEnabledFlag {
4015 #** @class Geo::OGR::DataSource
4016 # @brief A vector dataset.
4017 # @details This is a legacy class which should not be
4018 # used in new code. Use Geo::GDAL::Dataset.
4020 package Geo::OGR::DataSource;
4022 #** @method Geo::GDAL::Dataset Open()
4023 # Package subroutine.
4024 # The same as Geo::OGR::Open
4029 #** @method Geo::GDAL::Dataset OpenShared()
4030 # Package subroutine.
4031 # The same as Geo::OGR::OpenShared
4036 #** @class Geo::OGR::Driver
4037 # @brief A vector format driver.
4038 # @details This is a legacy class which
4039 # should not be used in new code. Use Geo::GDAL::Driver.
4041 package Geo::OGR::Driver;
4043 use base qw(Geo::GDAL::Driver)
4045 #** @method Geo::GDAL::Dataset Copy(Geo::GDAL::Dataset source, $name, arrayref options = undef)
4047 # Copy a vector data source into a new data source with this driver.
4048 # @param source The Geo::GDAL::Dataset object to be copied.
4049 # @param name The name for the new data source.
4050 # @param options Driver specific options. In addition to options
4051 # specified in GDAL documentation the option STRICT can be set to 'NO'
4052 # for a more relaxed copy. Otherwise the STRICT is 'YES'.
4053 # @note The order of the first two parameters is different from that in Geo::GDAL::Driver::Copy.
4054 # @return a new Geo::GDAL::Dataset object.
4057 my ($self, @p) = @_; # src, name, options
4058 my $strict = 1; # the default in bindings
4059 $strict = 0 if $p[2] && $p[2]->{STRICT} eq 'NO';
4060 $self->SUPER::Copy($p[1], $p[0], $strict, @{$p[2..4]}); # path, src, strict, options, cb, cb_data
4063 #** @method Geo::GDAL::Dataset Create($name, hashref options = undef )
4065 # Create a new vector data source using this driver.
4066 # @param name The data source name.
4067 # @param options Driver specific dataset creation options.
4070 my ($self, $name, $options) = @_; # name, options
4072 $self->SUPER::Create(Name => $name, Width => 0, Height => 0, Bands => 0, Type => 'Byte', Options => $options);
4077 # The same as Geo::OGR::Open except that only this driver is allowed.
4081 my @p = @_; # name, update
4082 my @flags = qw/VECTOR/;
4083 push @flags, qw/UPDATE/ if $p[1];
4084 my $dataset = Geo::GDAL::OpenEx($p[0], \@flags, [$self->Name()]);
4085 error("Failed to open $p[0]. Is it a vector dataset?") unless $dataset;
4089 #** @class Geo::OGR::Feature
4090 # @brief A collection of non-spatial and spatial attributes.
4091 # @details A feature is a collection of non-spatial and spatial attributes and
4092 # an id, which is a special attribute, and data records according to
4093 # this data model. Attributes are called fields and some fields are
4094 # spatial, i.e., their value is a geometry. Fields have at least a
4095 # name and a type. Features may exist within a layer or
4096 # separetely. The data model of a feature is a definition object.
4098 package Geo::OGR::Feature;
4100 use base qw(Geo::OGR)
4102 #** @method Geo::OGR::Feature Clone()
4104 # @return a new Geo::OGR::Feature object
4109 #** @method DumpReadable()
4111 # Write the contents of this feature to stdout.
4116 #** @method scalar Equal($feature)
4118 # @param feature a Geo::OGR::Feature object for comparison
4124 #** @method scalar FID($id)
4126 # @brief Get or set the id of this feature.
4127 # @param id [optional] the id to set for this feature.
4128 # @return integer the id of this feature.
4132 $self->SetFID($_[0]) if @_;
4133 return unless defined wantarray;
4137 #** @method Field($name, $value, ...)
4139 # @brief Get, set, or unset the field value.
4140 # @param name the name (or the index) of the field.
4141 # @param value a scalar, a list of scalars or a reference to a
4142 # list. If undef, the field is unset. If a scalar or a list of
4143 # scalars, the field is set from them.
4144 # @note Non-scalar fields (for example Date) can be set either from a
4145 # scalar, which is then assumed to be a string and parsed, or from a
4146 # list of values (for example year, month, day for Date).
4147 # @note Setting and getting Integer64 fields requires 'use bigint' if
4148 # \$Config{ivsize} is smaller than 8, i.e., in a 32 bit machine.
4149 # @return in non-void context the value of the field, which may be a
4150 # scalar or a list, depending on the field type. For unset fields the
4151 # undef value is returned.
4155 my $field = $self->GetFieldIndex(shift // 0);
4156 $self->SetField($field, @_) if @_;
4157 $self->GetField($field) if defined wantarray;
4160 #** @method FillUnsetWithDefault()
4162 sub FillUnsetWithDefault {
4165 #** @method Geometry($name, $geometry)
4167 # @brief Get or set the value of a geometry field.
4168 # @note This method delivers the functionality of undocumented methods
4169 # SetGeometry($geometry), SetGeometryDirectly, SetGeomField,
4170 # SetGeomFieldDirectly, GetGeometry, GetGeometryRef.
4172 # Set or get the geometry in the feature. When setting, does a check
4173 # against the schema (GeometryType) of the feature. If the parameter
4174 # is a geometry object, it is cloned.
4175 # @param name [optional] the name of the spatial field,
4176 # whose geometry is to be set. If not given, sets or gets the geometry
4177 # of the first (or the single) spatial field.
4178 # @param geometry [optional] a Geo::OGR::Geometry object or a
4179 # reference to a hash from which such can be created (using
4180 # Geo::OGR::Geometry::new).
4181 # @return in a non-void context the indicated geometry in the feature
4182 # as a Geo::OGR::Geometry object. The returned object contains a
4183 # reference to the actual geometry data in the feature (the geometry
4184 # is not cloned) and to the feature object, thus keeping the feature
4185 # object from being destroyed while the geometry object exists.
4189 my $field = ((@_ > 0 and ref($_[0]) eq '') or (@_ > 2 and @_ % 2 == 1)) ? shift : 0;
4190 $field = $self->GetGeomFieldIndex($field);
4192 if (@_ and @_ % 2 == 0) {
4198 my $type = $self->GetDefn->GetGeomFieldDefn($field)->Type;
4199 if (blessed($geometry) and $geometry->isa('Geo::OGR::Geometry')) {
4200 my $gtype = $geometry->GeometryType;
4201 error("The type of the inserted geometry ('$gtype') is not the same as the type of the field ('$type').")
4202 if $type ne 'Unknown' and $type ne $gtype;
4204 $self->SetGeomFieldDirectly($field, $geometry->Clone);
4206 confess last_error() if $@;
4207 } elsif (ref($geometry) eq 'HASH') {
4208 $geometry->{GeometryType} //= $type;
4210 $geometry = Geo::OGR::Geometry->new($geometry);
4212 confess last_error() if $@;
4213 my $gtype = $geometry->GeometryType;
4214 error("The type of the inserted geometry ('$gtype') is not the same as the type of the field ('$type').")
4215 if $type ne 'Unknown' and $type ne $gtype;
4217 $self->SetGeomFieldDirectly($field, $geometry);
4219 confess last_error() if $@;
4221 error("Usage: \$feature->Geometry([field],[geometry])");
4224 return unless defined wantarray;
4225 $geometry = $self->GetGeomFieldRef($field);
4226 return unless $geometry;
4227 keep($geometry, $self);
4230 #** @method Geo::OGR::FeatureDefn GetDefn()
4232 # @note A.k.a GetDefnRef.
4233 # @return a Geo::OGR::FeatureDefn object, which represents the definition of this feature.
4237 my $defn = $self->GetDefnRef;
4241 #** @method scalar GetFID()
4243 # @return the feature id (an integer).
4248 #** @method list GetField($name)
4253 my ($self, $field) = @_;
4254 $field = $self->GetFieldIndex($field);
4255 return unless IsFieldSet($self, $field);
4256 my $type = GetFieldType($self, $field);
4257 return GetFieldAsInteger($self, $field) if $type == $Geo::OGR::OFTInteger;
4258 return GetFieldAsInteger64($self, $field) if $type == $Geo::OGR::OFTInteger64;
4259 return GetFieldAsDouble($self, $field) if $type == $Geo::OGR::OFTReal;
4260 return GetFieldAsString($self, $field) if $type == $Geo::OGR::OFTString;
4261 if ($type == $Geo::OGR::OFTIntegerList) {
4262 my $ret = GetFieldAsIntegerList($self, $field);
4263 return wantarray ? @$ret : $ret;
4265 if ($type == $Geo::OGR::OFTInteger64List) {
4266 my $ret = GetFieldAsInteger64List($self, $field);
4267 return wantarray ? @$ret : $ret;
4269 if ($type == $Geo::OGR::OFTRealList) {
4270 my $ret = GetFieldAsDoubleList($self, $field);
4271 return wantarray ? @$ret : $ret;
4273 if ($type == $Geo::OGR::OFTStringList) {
4274 my $ret = GetFieldAsStringList($self, $field);
4275 return wantarray ? @$ret : $ret;
4277 if ($type == $Geo::OGR::OFTBinary) {
4278 return GetFieldAsBinary($self, $field);
4280 if ($type == $Geo::OGR::OFTDate) {
4281 my @ret = GetFieldAsDateTime($self, $field);
4282 # year, month, day, hour, minute, second, timezone
4283 return wantarray ? @ret[0..2] : [@ret[0..2]];
4285 if ($type == $Geo::OGR::OFTTime) {
4286 my @ret = GetFieldAsDateTime($self, $field);
4287 return wantarray ? @ret[3..6] : [@ret[3..6]];
4289 if ($type == $Geo::OGR::OFTDateTime) {
4290 my @ret = GetFieldAsDateTime($self, $field);
4291 return wantarray ? @ret : [@ret];
4293 error("Perl bindings do not support the field type '".i2s(field_type => $type)."'.");
4296 #** @method scalar GetFieldDefn($name)
4298 # Get the definition of a field.
4299 # @param name the name of the field.
4300 # @return a Geo::OGR::FieldDefn object.
4304 my $field = $self->GetFieldIndex(shift);
4305 return $self->GetFieldDefnRef($field);
4308 #** @method list GetFieldNames()
4310 # Get the names of the fields in this feature.
4315 #** @method scalar GetGeomFieldDefn($name)
4317 # Get the definition of a spatial field.
4318 # @param name the name of the spatial field.
4319 # @return a Geo::OGR::GeomFieldDefn object.
4321 sub GetGeomFieldDefn {
4323 my $field = $self->GetGeomFieldIndex(shift);
4324 return $self->GetGeomFieldDefnRef($field);
4327 #** @method GetNativeData()
4332 #** @method GetNativeMediaType()
4334 sub GetNativeMediaType {
4337 #** @method hash reference GetSchema()
4339 # @brief Get the schema of this feature.
4341 # @return the schema as a hash whose keywords are Name, StyleIgnored
4342 # and Fields. Fields is an anonymous array of first non-spatial and
4343 # then spatial field schemas as in Geo::OGR::FieldDefn::Schema() and
4344 # Geo::OGR::GeomFieldDefn::Schema().
4348 error("Schema of a feature cannot be set directly.") if @_;
4349 return $self->GetDefnRef->Schema;
4352 #** @method scalar GetStyleString()
4356 sub GetStyleString {
4359 #** @method IsFieldNull()
4364 #** @method IsFieldSetAndNotNull()
4366 sub IsFieldSetAndNotNull {
4369 #** @method Geo::OGR::Layer Layer()
4371 # @return the layer to which this feature belongs to or undef.
4378 #** @method hash reference Row(%row)
4380 # @note This method discards the data the destination feature (or
4381 # layer) does not support. Changes in data due to differences between
4382 # field types may also occur.
4384 # Get and/or set the data of the feature. The key of the (key,value)
4385 # pairs of the row is the field name. Special field names FID and
4386 # Geometry are used for feature id and (single) geometry
4387 # respectively. The geometry/ies is/are set and get using the
4388 # Geo::OGR::Feature::Geometry method. Field values are set using the
4389 # Geo::OGR::Feature::Field method.
4390 # @param row [optional] feature data in a hash.
4391 # @return a reference to feature data in a hash. Spatial fields are
4392 # returned as Geo::OGR::Geometry objects.
4396 my $nf = $self->GetFieldCount;
4397 my $ngf = $self->GetGeomFieldCount;
4400 if (@_ == 1 and ref($_[0]) eq 'HASH') {
4402 } elsif (@_ and @_ % 2 == 0) {
4405 error('Usage: $feature->Row(%FeatureData).');
4407 $self->SetFID($row{FID}) if defined $row{FID};
4408 #$self->Geometry($schema, $row{Geometry}) if $row{Geometry};
4409 for my $name (keys %row) {
4410 next if $name eq 'FID';
4411 if ($name eq 'Geometry') {
4412 $self->Geometry(0, $row{$name});
4416 for my $i (0..$nf-1) {
4417 if ($self->GetFieldDefnRef($i)->Name eq $name) {
4418 $self->SetField($i, $row{$name});
4424 for my $i (0..$ngf-1) {
4425 if ($self->GetGeomFieldDefnRef($i)->Name eq $name) {
4426 $self->Geometry($i, $row{$name});
4432 carp "Unknown field: '$name'.";
4435 return unless defined wantarray;
4437 for my $i (0..$nf-1) {
4438 my $name = $self->GetFieldDefnRef($i)->Name;
4439 $row{$name} = $self->GetField($i);
4441 for my $i (0..$ngf-1) {
4442 my $name = $self->GetGeomFieldDefnRef($i)->Name || 'Geometry';
4443 $row{$name} = $self->GetGeometry($i);
4445 $row{FID} = $self->GetFID;
4449 #** @method SetFID($id)
4451 # @param id the feature id.
4456 #** @method SetField($name, @Value)
4462 my $field = $self->GetFieldIndex(shift);
4464 if (@_ == 0 or !defined($arg)) {
4465 _UnsetField($self, $field);
4468 $arg = [@_] if @_ > 1;
4469 my $type = $self->GetFieldType($field);
4471 if ($type == $Geo::OGR::OFTIntegerList) {
4472 SetFieldIntegerList($self, $field, $arg);
4474 elsif ($type == $Geo::OGR::OFTInteger64List) {
4475 SetFieldInteger64List($self, $field, $arg);
4477 elsif ($type == $Geo::OGR::OFTRealList) {
4478 SetFieldDoubleList($self, $field, $arg);
4480 elsif ($type == $Geo::OGR::OFTStringList) {
4481 SetFieldStringList($self, $field, $arg);
4483 elsif ($type == $Geo::OGR::OFTDate) {
4484 _SetField($self, $field, @$arg[0..2], 0, 0, 0, 0);
4486 elsif ($type == $Geo::OGR::OFTTime) {
4488 _SetField($self, $field, 0, 0, 0, @$arg[0..3]);
4490 elsif ($type == $Geo::OGR::OFTDateTime) {
4492 _SetField($self, $field, @$arg[0..6]);
4494 elsif ($type == $Geo::OGR::OFTInteger64)
4496 SetFieldInteger64($self, $field, $arg);
4499 $type = i2s(field_type => $type);
4500 my $name = $self->GetFieldDefnRef($field)->Name;
4501 error("'$arg' is not a suitable value for field $name($type).");
4504 if ($type == $Geo::OGR::OFTBinary) {
4505 #$arg = unpack('H*', $arg); # remove when SetFieldBinary is available
4506 $self->SetFieldBinary($field, $arg);
4508 elsif ($type == $Geo::OGR::OFTInteger64)
4510 SetFieldInteger64($self, $field, $arg);
4512 elsif ($type == $Geo::OGR::OFTInteger or $type == $Geo::OGR::OFTReal or $type == $Geo::OGR::OFTString)
4514 _SetField($self, $field, $arg);
4517 $type = i2s(field_type => $type);
4518 my $name = $self->GetFieldDefnRef($field)->Name;
4519 error("'$arg' is not a suitable value for field $name($type).");
4524 #** @method SetFieldNull()
4529 #** @method SetFrom($other, $forgiving = 1, hashref map)
4531 # @param other a Geo::OGR::Feature object
4532 # @param forgiving [optional] set to false if the operation should not
4533 # continue if output fields do not match some of the source fields
4534 # @param map [optional] a mapping from output field indexes to source
4535 # fields, include into the hash all field indexes of this feature
4536 # which should be set
4539 my($self, $other) = @_;
4540 _SetFrom($self, $other), return if @_ <= 2;
4541 my $forgiving = $_[2];
4542 _SetFrom($self, $other, $forgiving), return if @_ <= 3;
4545 for my $i (1..GetFieldCount($self)) {
4546 push @list, ($map->{$i} || -1);
4548 SetFromWithMap($self, $other, 1, \@list);
4551 #** @method SetNativeData()
4556 #** @method SetNativeMediaType()
4558 sub SetNativeMediaType {
4561 #** @method SetStyleString($string)
4565 sub SetStyleString {
4568 #** @method list Tuple(@tuple)
4570 # @note This method discards the data the destination feature (or
4571 # layer) does not support. Changes in data due to differences between
4572 # field types may also occur.
4574 # @note The schema of the tuple needs to be the same as that of the
4577 # Get and/set the data of the feature. The expected data in the tuple
4578 # is ([feature_id,] non-spatial fields, spatial fields). The fields in
4579 # the tuple are in the order they are in the schema. Field values are
4580 # set using the Geo::OGR::Feature::Field method. Geometries are set
4581 # and get using the Geo::OGR::Feature::Geometry method.
4582 # @param tuple [optional] feature data in an array
4583 # @return feature data in an array
4587 my $nf = $self->GetFieldCount;
4588 my $ngf = $self->GetGeomFieldCount;
4590 my $values = ref $_[0] ? $_[0] : \@_;
4592 $FID = shift @$values if @$values == $nf + $ngf + 1;
4593 $self->SetFID($FID) if defined $FID;
4594 if (@$values != $nf + $ngf) {
4596 error("Too many or too few attribute values for a feature (need $n).");
4598 my $index = 0; # index to non-geometry and geometry fields
4599 for my $i (0..$nf-1) {
4600 $self->SetField($i, $values->[$i]);
4602 for my $i (0..$ngf-1) {
4603 $self->Geometry($i, $values->[$nf+$i]);
4606 return unless defined wantarray;
4607 my @ret = ($self->GetFID);
4608 for my $i (0..$nf-1) {
4609 my $v = $self->GetField($i);
4612 for my $i (0..$ngf-1) {
4613 my $v = $self->GetGeometry($i);
4619 #** @method scalar Validate(list flags)
4621 # @param flags one of more of null, geom_type, width,
4622 # allow_null_when_default, or all.
4623 # @exception croaks with an error message if the feature is not valid.
4624 # @return integer denoting the validity of the feature object.
4630 my $f = eval '$Geo::OGR::'.uc($flag);
4633 _Validate($self, $flags);
4636 #** @method Geo::OGR::Feature new(%schema)
4638 # @brief Create a new feature.
4639 # @param Named parameters:
4640 # - \a Schema a reference to a schema hash, or a Geo::OGR::Layer,
4641 # Geo::OGR::Feature, or Geo::OGR::FeatureDefn object.
4642 # - \a Values values for the feature attributes.
4643 # - \a StyleIgnored whether the style can be omitted when fetching
4644 # features. (default is false)
4646 # Schema is a hash with the following keys:
4647 # - \a Name name of the schema (not used).
4648 # - \a Fields a list of Geo::OGR::FieldDefn or Geo::OGR::GeomFieldDefn
4649 # objects or references to hashes from which fields can be created.
4650 # - \a GeometryType the geometry type if the feature has only one spatial field.
4652 # @note Do not mix GeometryType and geometry fields in Fields list.
4653 # @note Old syntax where the argument is a Geo::OGR::FeatureDefn
4654 # object or Schema hash is supported.
4656 # @return a new Geo::OGR::Feature object.
4662 if (ref $_[0] eq 'HASH' && $_[0]->{Schema}) {
4665 $arg = {Schema => $_[0]};
4667 } elsif (@_ and @_ % 2 == 0) {
4669 unless ($arg->{Schema}) {
4671 $arg->{Schema} = \%tmp;
4674 error("The argument must be either a schema or a hash.");
4676 error("Missing schema.") unless $arg->{Schema};
4678 for (ref $arg->{Schema}) {
4679 (/Geo::OGR::Layer$/ || /Geo::OGR::Feature$/) && do {
4680 $defn = $arg->{Schema}->GetDefn;
4683 /Geo::OGR::FeatureDefn$/ && do {
4684 $defn = $arg->{Schema};
4687 $defn = Geo::OGR::FeatureDefn->new($arg->{Schema});
4689 my $self = Geo::OGRc::new_Feature($defn);
4690 error("Feature creation failed.") unless $self;
4692 for (ref $arg->{Values}) {
4694 $self->Tuple($arg->{Values});
4698 $self->Row($arg->{Values});
4701 /Geo::OGR::Feature$/ && do {
4702 $self->Tuple($arg->{Values}->Tuple);
4708 error("Value parameter must be an array, hash, or another feature. Not $_.");
4713 #** @class Geo::OGR::FeatureDefn
4714 # @brief The schema of a feature or a layer.
4715 # @details A FeatureDefn object is a collection of field definition objects. A
4716 # read-only FeatureDefn object can be obtained from a layer
4717 # (Geo::OGR::Layer::GetDefn()) or a feature
4718 # (Geo::OGR::Feature::GetDefn()).
4720 package Geo::OGR::FeatureDefn;
4722 use base qw(Geo::OGR)
4724 #** @method AddField(%params)
4726 # @param params Named parameters to create a new Geo::OGR::FieldDefn
4727 # or Geo::OGR::GeomFieldDefn object.
4731 error("Read-only definition.") if parent($self);
4734 } elsif (ref($_[0]) eq 'HASH') {
4736 } elsif (@_ % 2 == 0) {
4739 $params{Type} //= '';
4740 if (s_exists(field_type => $params{Type})) {
4741 my $fd = Geo::OGR::FieldDefn->new(%params);
4742 $self->AddFieldDefn($fd);
4744 my $fd = Geo::OGR::GeomFieldDefn->new(%params);
4745 $self->AddGeomFieldDefn($fd);
4749 #** @method DeleteField($name)
4751 # @note Currently only geometry fields can be deleted.
4752 # @param index the index of the geometry field to be deleted.
4755 my ($self, $name) = @_;
4756 error("Read-only definition.") if parent($self);
4757 for my $i (0..$self->GetFieldCount-1) {
4758 error("Non-spatial fields cannot be deleted.") if $self->_GetFieldDefn($i)->Name eq $name;
4760 for my $i (0..$self->GetGeomFieldCount-1) {
4761 $self->DeleteGeomFieldDefn($i) if $self->_GetGeomFieldDefn($i)->Name eq $name;
4763 error(2, $name, 'Field');
4766 #** @method Feature()
4770 return parent($self);
4773 #** @method scalar GetFieldDefn($name)
4775 # Get the definition of a field.
4776 # @param name the name of the field.
4777 # @return a Geo::OGR::FieldDefn object.
4781 my $field = $self->GetFieldIndex(shift);
4782 return $self->_GetFieldDefn($field);
4785 #** @method list GetFieldNames()
4787 # The names of the fields in this layer or feature definition.
4788 # @return the list of field names.
4793 for my $i (0..$self->GetFieldCount-1) {
4794 push @names, $self->_GetFieldDefn($i)->Name;
4796 for my $i (0..$self->GetGeomFieldCount-1) {
4797 push @names, $self->_GetGeomFieldDefn($i)->Name;
4802 #** @method scalar GetGeomFieldDefn($name)
4804 # Get the definition of a spatial field.
4805 # @param name the name of the spatial field.
4806 # @return a Geo::OGR::GeomFieldDefn object.
4808 sub GetGeomFieldDefn {
4810 my $field = $self->GetGeomFieldIndex(shift);
4811 return $self->_GetGeomFieldDefn($field);
4814 #** @method scalar GetName()
4816 # @return the name of this layer or feature definition.
4821 #** @method hash reference GetSchema()
4823 # @brief Get the schema of this feature or layer definition.
4825 # @return the schema as a hash whose keywords are Name, StyleIgnored
4826 # and Fields. Fields is an anonymous array of first non-spatial and
4827 # then spatial field schemas as in Geo::OGR::FieldDefn::Schema() and
4828 # Geo::OGR::GeomFieldDefn::Schema().
4832 carp "Schema of a feature definition should not be set directly." if @_;
4833 if (@_ and @_ % 2 == 0) {
4835 if ($schema{Fields}) {
4836 for my $field (@{$schema{Fields}}) {
4837 $self->AddField($field);
4842 $schema{Name} = $self->Name();
4843 $schema{StyleIgnored} = $self->StyleIgnored();
4844 $schema{Fields} = [];
4845 for my $i (0..$self->GetFieldCount-1) {
4846 my $s = $self->_GetFieldDefn($i)->Schema;
4847 push @{$schema{Fields}}, $s;
4849 for my $i (0..$self->GetGeomFieldCount-1) {
4850 my $s = $self->_GetGeomFieldDefn($i)->Schema;
4851 push @{$schema{Fields}}, $s;
4853 return wantarray ? %schema : \%schema;
4856 #** @method IsSame(Geo::OGR::FeatureDefn defn)
4858 # @return true if this definition is similar to the other definition,
4864 #** @method scalar IsStyleIgnored()
4866 # Get the ignore status of style information when fetching features.
4867 # @return the ignore status of style information
4870 sub IsStyleIgnored {
4873 #** @method SetStyleIgnored($IgnoreState)
4875 # Set the ignore status of style information when fetching features.
4878 sub SetStyleIgnored {
4881 #** @method Geo::OGR::FeatureDefn new(%schema)
4883 # Creates a new layer or feature definition. The new definition is
4884 # either initialized to the given schema or it will contain no
4885 # non-spatial fields and one spatial field, whose Name is '' and
4886 # GeometryType is 'Unknown' or the value of the named parameter
4888 # @param schema [optional] The schema for the new feature definition,
4889 # as in Geo::OGR::FeatureDefn::Schema().
4890 # @return a Geo::OGR::FeatureDefn object
4894 # $fd = Geo::OGR::FeatureDefn->new(
4896 # Fields => [{ Name => 'field1', Type => 'String' },
4897 # { Name => 'geom', GeometryType => 'Point' }] );
4903 if (@_ == 1 and ref($_[0]) eq 'HASH') {
4905 } elsif (@_ and @_ % 2 == 0) {
4908 my $fields = $schema{Fields};
4909 error("The 'Fields' argument must be an array reference.") if $fields and ref($fields) ne 'ARRAY';
4910 $schema{Name} //= '';
4911 my $self = Geo::OGRc::new_FeatureDefn($schema{Name});
4913 my $gt = $schema{GeometryType};
4915 $self->GeometryType($gt);
4917 $self->DeleteGeomFieldDefn(0);
4919 $self->StyleIgnored($schema{StyleIgnored}) if exists $schema{StyleIgnored};
4920 for my $fd (@{$fields}) {
4922 if (ref($fd) eq 'HASH') {
4923 # if Name and Type are missing, assume Name => Type
4924 if (!(exists $fd->{Name} && exists $fd->{Type})) {
4925 for my $key (sort keys %$fd) {
4926 if (s_exists(field_type => $fd->{$key}) ||
4927 s_exists(geometry_type => $fd->{$key}))
4930 $fd->{Type} = $fd->{$key};
4936 if ($fd->{GeometryType} or ($fd->{Type} && s_exists(geometry_type => $fd->{Type}))) {
4937 $d = Geo::OGR::GeomFieldDefn->new(%$fd);
4939 $d = Geo::OGR::FieldDefn->new(%$fd);
4942 if (blessed($d) and $d->isa('Geo::OGR::FieldDefn')) {
4943 AddFieldDefn($self, $d);
4944 } elsif (blessed($d) and $d->isa('Geo::OGR::GeomFieldDefn')) {
4945 error("Do not mix GeometryType and geometry fields in Fields.") if $gt;
4946 AddGeomFieldDefn($self, $d);
4948 error("Item in field list does not define a field.");
4954 #** @class Geo::OGR::FieldDefn
4955 # @brief A definition of a non-spatial attribute.
4958 package Geo::OGR::FieldDefn;
4960 use base qw(Geo::OGR)
4962 #** @method scalar Default($value)
4964 # Get or set the default value for this field.
4965 # @note a.k.a. GetDefault and SetDefault
4966 # @param value [optional]
4967 # @return the default value of this field in non-void context.
4971 SetDefault($self, $_[0]) if @_;
4972 GetDefault($self) if defined wantarray;
4975 #** @method GetSchema()
4980 #** @method scalar Ignored($ignore)
4982 # Get and/or set the ignore status (whether this field should be
4983 # omitted when fetching features) of this field.
4984 # @note a.k.a. IsIgnored, SetIgnored
4985 # @param ignore [optional]
4986 # @return the ignore status of this field in non-void context.
4991 SetIgnored($self, $_[0]) if @_;
4992 IsIgnored($self) if defined wantarray;
4995 #** @method IsDefaultDriverSpecific()
4997 sub IsDefaultDriverSpecific {
5000 #** @method scalar Justify($justify)
5002 # Get and/or set the justification of this field.
5003 # @note a.k.a. GetJustify, SetJustify
5004 # @param justify [optional] One of field justify types (Geo::OGR::FieldDefn::JustifyValues).
5005 # @return the justify value of this field in non-void context.
5008 my($self, $justify) = @_;
5009 if (defined $justify) {
5010 $justify = s2i(justify => $justify);
5011 SetJustify($self, $justify);
5013 return i2s(justify => GetJustify($self)) if defined wantarray;
5016 #** @method list JustifyValues()
5017 # Package subroutine.
5018 # Justify values supported by GDAL. Current list is
5019 # Left, Right, and Undefined.
5025 #** @method scalar Name($name)
5027 # Get and/or set the name of the field.
5028 # @note a.k.a. GetName, GetNameRef, SetName
5029 # @param name [optional]
5030 # @return the name in non-void context
5034 SetName($self, $_[0]) if @_;
5035 GetName($self) if defined wantarray;
5038 #** @method scalar Nullable($nullable)
5040 # Get or set the nullable constraint for this field.
5041 # @note a.k.a. IsNullable and SetNullable
5042 # @param nullable [optional]
5043 # @return the nullable value of this field in non-void context.
5047 SetNullable($self, $_[0]) if @_;
5048 IsNullable($self) if defined wantarray;
5051 #** @method scalar Precision($precision)
5053 # Get and/or set the precision of this field.
5054 # @note a.k.a. GetPrecision, SetPrecision
5055 # @param precision [optional]
5056 # @return the precision of this field in non-void context.
5060 SetPrecision($self, $_[0]) if @_;
5061 GetPrecision($self) if defined wantarray;
5064 #** @method hash reference Schema(%params)
5066 # Get the schema or set parts of the schema
5067 # @param params [optional] as those in Geo::OGR::FieldDefn::new.
5068 # @return a reference to a hash whose keys are as those in Geo::OGR::FieldDefn::new.
5073 my $params = @_ % 2 == 0 ? {@_} : shift;
5074 for my $key (keys %SCHEMA_KEYS) {
5075 next unless exists $params->{$key};
5076 eval "\$self->$key(\$params->{$key})";
5077 confess(last_error()) if $@;
5080 return unless defined wantarray;
5082 for my $key (keys %SCHEMA_KEYS) {
5083 $schema{$key} = eval '$self->'.$key;
5085 return wantarray ? %schema : \%schema;
5088 #** @method SetSchema()
5093 #** @method scalar SubType($SubType)
5095 # @note a.k.a. GetSubType, SetSubType
5096 # @param SubType [optional] One of field sub types (Geo::OGR::FieldDefn::SubTypes).
5097 # @return the sub type of this field in non-void context.
5100 my($self, $subtype) = @_;
5101 if (defined $subtype) {
5102 $subtype = s2i(field_subtype => $subtype);
5103 SetSubType($self, $subtype);
5105 return i2s(field_subtype => GetSubType($self)) if defined wantarray;
5108 #** @method SubTypes()
5114 #** @method scalar Type($type)
5116 # Get and/or set the type of the field.
5117 # @note a.k.a. GetFieldTypeName, GetTypeName, GetType, SetType
5118 # @param type [optional] One of field types (Geo::OGR::FieldDefn::Types).
5119 # @return one of field types in non-void context.
5122 my($self, $type) = @_;
5123 if (defined $type) {
5124 $type = s2i(field_type => $type);
5125 SetType($self, $type);
5127 return i2s(field_type => GetType($self)) if defined wantarray;
5130 #** @method list Types()
5131 # Package subroutine.
5132 # Field types supported by GDAL. Current list is
5133 # Binary, Date, DateTime, Integer, Integer64, Integer64List, IntegerList, Real, RealList, String, StringList, Time, WideString, and WideStringList.
5134 # (However, WideString is not supported.)
5140 #** @method scalar Width($width)
5142 # Get and/or set the field width.
5143 # @note a.k.a. GetWidth, SetWidth
5144 # @param width [optional]
5145 # @return the width of this field in non-void context.
5149 SetWidth($self, $_[0]) if @_;
5150 GetWidth($self) if defined wantarray;
5153 #** @method Geo::OGR::FieldDefn new(%params)
5155 # @brief Create a new field definition.
5157 # @param Named parameters:
5158 # - \a Name Field name (default is 'unnamed').
5159 # - \a Type Field type, one of Geo::OGR::FieldDefn::Types (default is 'String').
5160 # - \a SubType Field sub type, one of Geo::OGR::FieldDefn::SubTypes.
5161 # - \a Justify Justify value, one of Geo::OGR::FieldDefn::JustifyValues
5164 # - \a Nullable (default is true)
5166 # - \a Ignored (default is false)
5168 # @note Simplified parameters Name => 'Type' are also supported.
5170 # @return a new Geo::OGR::FieldDefn object
5174 my $params = {Name => 'unnamed', Type => 'String'};
5176 } elsif (@_ == 1 and not ref $_[0]) {
5177 $params->{Name} = shift;
5178 } elsif (@_ == 2 and not $Geo::OGR::FieldDefn::SCHEMA_KEYS{$_[0]}) {
5179 $params->{Name} = shift;
5180 $params->{Type} = shift;
5182 my $tmp = @_ % 2 == 0 ? {@_} : shift;
5183 for my $key (keys %$tmp) {
5184 if ($Geo::OGR::FieldDefn::SCHEMA_KEYS{$key}) {
5185 $params->{$key} = $tmp->{$key};
5187 carp "Unknown parameter: '$key'." if $key ne 'Index';
5191 $params->{Type} = s2i(field_type => $params->{Type});
5192 my $self = Geo::OGRc::new_FieldDefn($params->{Name}, $params->{Type});
5194 delete $params->{Name};
5195 delete $params->{Type};
5196 $self->Schema($params);
5200 #** @class Geo::OGR::GeomFieldDefn
5201 # @brief A definition of a spatial attribute.
5204 package Geo::OGR::GeomFieldDefn;
5206 use base qw(Geo::OGR)
5208 #** @method scalar GeometryType($type)
5210 # @note a.k.a. GetType, SetType
5211 # @return the geometry type of the field.
5216 #** @method GetSchema()
5221 #** @method scalar Ignored($ignore)
5223 # @note a.k.a. IsIgnored, SetIgnored
5224 # @return the ignore status of the field.
5228 SetIgnored($self, $_[0]) if @_;
5229 IsIgnored($self) if defined wantarray;
5232 #** @method scalar Name($name)
5234 # @note a.k.a. GetName, GetNameRef, SetName
5235 # @return the name of the field.
5239 SetName($self, $_[0]) if @_;
5240 GetName($self) if defined wantarray;
5243 #** @method scalar Nullable($nullable)
5245 # @note a.k.a. IsNullable, SetNullable
5246 # @return the nullable status of the field.
5250 SetNullable($self, $_[0]) if @_;
5251 IsNullable($self) if defined wantarray;
5254 #** @method hash reference Schema(%params)
5256 # Get the schema or set parts of the schema.
5257 # @param params [optional] as those in Geo::OGR::GeomFieldDefn::new.
5258 # @return a reference to a hash whose keys are as those in Geo::OGR::GeomFieldDefn::new.
5263 my $params = @_ % 2 == 0 ? {@_} : shift;
5264 for my $key (keys %SCHEMA_KEYS) {
5265 next unless exists $params->{$key};
5266 eval "\$self->$key(\$params->{$key})";
5267 confess last_error() if $@;
5270 return unless defined wantarray;
5272 for my $key (keys %SCHEMA_KEYS) {
5273 $schema{$key} = eval '$self->'.$key;
5275 return wantarray ? %schema : \%schema;
5278 #** @method SetSchema()
5283 #** @method scalar SpatialReference($sr)
5285 # @note a.k.a. GetSpatialRef, SetSpatialRef
5286 # @return the spatial reference of the field as a Geo::OSR::SpatialReference object.
5288 sub SpatialReference {
5290 SetSpatialRef($self, $_[0]) if @_;
5291 GetSpatialRef($self) if defined wantarray;
5296 # @return the type of this geometry field. One of Geo::OGR::GeomFieldDefn::Types
5299 my($self, $type) = @_;
5300 if (defined $type) {
5301 $type = s2i(geometry_type => $type);
5302 SetType($self, $type);
5304 i2s(geometry_type => GetType($self)) if defined wantarray;
5308 # Package subroutine.
5309 # @return a list of all geometry types, currently:
5310 # 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.
5313 return Geo::OGR::Geometry::GeometryTypes();
5316 #** @method Geo::OGR::GeomFieldDefn new(%params)
5318 # @brief Create a new spatial field definition.
5320 # @param params one or more of:
5321 # - \a Name name for the field (default is 'geom').
5322 # - \a GeometryType type for the field type, one of Geo::OGR::GeomFieldDefn::Types (default is 'Unknown').
5323 # - \a SpatialReference a Geo::OSR::SpatialReference object.
5324 # - \a Nullable (default is true)
5325 # - \a Ignored (default is false)
5327 # @note Simplified parameters <name> => <type> is also supported.
5329 # @return a new Geo::OGR::GeomFieldDefn object
5333 my $params = {Name => 'geom', Type => 'Unknown'};
5336 $params->{Name} = shift;
5337 } elsif (@_ == 2 and not $Geo::OGR::GeomFieldDefn::SCHEMA_KEYS{$_[0]}) {
5338 $params->{Name} = shift;
5339 $params->{Type} = shift;
5341 my $tmp = @_ % 2 == 0 ? {@_} : shift;
5342 for my $key (keys %$tmp) {
5343 if ($Geo::OGR::GeomFieldDefn::SCHEMA_KEYS{$key}) {
5344 $params->{$key} = $tmp->{$key};
5346 carp "Unknown parameter: '$key'." if $key ne 'Index' && $key ne 'GeometryType';
5349 $params->{Type} //= $tmp->{GeometryType};
5351 $params->{Type} = s2i(geometry_type => $params->{Type});
5352 my $self = Geo::OGRc::new_GeomFieldDefn($params->{Name}, $params->{Type});
5354 delete $params->{Name};
5355 delete $params->{Type};
5356 $self->Schema($params);
5360 #** @class Geo::OGR::Geometry
5361 # @brief Spatial data.
5362 # @details A geometry is spatial data (coordinate values, and a reference to a
5363 # spatial reference system) organized into one of the geometry
5364 # types. Geometries can be created from several type of data including
5365 # a Perl data structure. There are several methods, which modify,
5366 # compare, test, or compute values from geometries.
5367 # @note Most spatial analysis methods require <a
5368 # href="http://geos.osgeo.org/doxygen/">GEOS</a> to work rigorously.
5370 package Geo::OGR::Geometry;
5372 use base qw(Geo::OGR)
5374 #** @method AddGeometry($other)
5376 # Add a copy of another geometry to a geometry collection
5377 # @param other a Geo::OGR::Geometry object
5382 #** @method AddGeometryDirectly($other)
5384 # @param other a Geo::OGR::Geometry object
5386 sub AddGeometryDirectly {
5389 #** @method AddPoint($x, $y, $z)
5391 # Set the data of a point or add a point to a line string. Consider
5392 # using Geo::OGR::Geometry::Points. Note that the coordinate
5393 # dimension is automatically upgraded to 25D (3) if z is given.
5396 # @param z [optional]
5397 # Calls internally the 2D or 3D version depending on the number of parameters.
5401 my $t = $self->GetGeometryType;
5402 my $has_z = HasZ($t);
5403 my $has_m = HasM($t);
5404 if (!$has_z && !$has_m) {
5405 $self->AddPoint_2D(@_[0..1]);
5406 } elsif ($has_z && !$has_m) {
5407 $self->AddPoint_3D(@_[0..2]);
5408 } elsif (!$has_z && $has_m) {
5409 $self->AddPointM(@_[0..2]);
5411 $self->AddPointZM(@_[0..3]);
5415 #** @method AddPointM()
5420 #** @method AddPointZM()
5425 #** @method AddPoint_2D($x, $y)
5427 # Set the data of a point or add a point to a line string. Consider
5428 # using Geo::OGR::Geometry::Points.
5435 #** @method AddPoint_3D($x, $y, $z)
5437 # Set the data of a point or add a point to a line string. Note that
5438 # the coordinate dimension is automatically upgraded to 25D (3). Consider
5439 # using Geo::OGR::Geometry::Points.
5447 #** @method Geo::OGR::Geometry ApproximateArcAngles(%params)
5448 # Package subroutine.
5449 # Create a line string, which approximates an arc.
5450 # @note All angles are in degrees.
5452 # @param %params Named parameters:
5453 # - \a Center center point (default is [0, 0, 0])
5454 # - \a PrimaryRadius default is 1.
5455 # - \a SecondaryAxis default is 1.
5456 # - \a Rotation default is 0.
5457 # - \a StartAngle default is 0.
5458 # - \a EndAngle default is 360.
5459 # - \a MaxAngleStepSizeDegrees default is 4.
5460 # @return a new Geo::OGR::Geometry object.
5462 sub ApproximateArcAngles {
5464 my %default = ( Center => [0,0,0],
5470 MaxAngleStepSizeDegrees => 4
5472 for my $p (keys %p) {
5473 if (exists $default{$p}) {
5474 $p{$p} //= $default{$p};
5476 carp "Unknown parameter: '$p'.";
5479 for my $p (keys %default) {
5480 $p{$p} //= $default{$p};
5482 error("Usage: Center => [x,y,z].") unless ref($p{Center}) eq 'ARRAY';
5484 $p{Center}->[$i] //= 0;
5486 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});
5489 #** @method scalar Area()
5491 # @note a.k.a. GetArea
5492 # @return the area of the polygon or multipolygon
5497 #** @method scalar As(%params)
5499 # Export the geometry into a known format.
5501 # @param params Named parameters:
5502 # - \a Format One of
5503 # - \a WKT Well Known Text.
5504 # - <em>ISO WKT</em>
5505 # - \a Text Same as WKT.
5506 # - \a WKB Well Known Binary.
5507 # - <em>ISO WKB</em>
5508 # - \a Binary Same as WKB.
5513 # - \a ByteOrder Byte order for binary formats. Default is 'XDR'.
5514 # - \a SRID Spatial reference id for HEXEWKB.
5515 # - \a Options GML generation options.
5516 # - \a AltitudeMode For KML.
5518 # @return the geometry in a given format.
5522 my $p = named_parameters(\@_, Format => undef, ByteOrder => 'XDR', SRID => undef, Options => undef, AltitudeMode => undef);
5523 my $f = $p->{format};
5524 if ($f =~ /text/i) {
5525 return $self->AsText;
5526 } elsif ($f =~ /wkt/i) {
5528 return $self->ExportToIsoWkt;
5530 return $self->AsText;
5532 } elsif ($f =~ /binary/i) {
5533 return $self->ExportToWkb($p->{byteorder});
5534 } elsif ($f =~ /wkb/i) {
5536 $p->{byteorder} = s2i(byte_order => $p->{byteorder});
5537 return $self->ExportToIsoWkb($p->{byteorder});
5538 } elsif ($f =~ /ewkb/i) {
5539 return $self->AsHEXEWKB($p->{srid});
5540 } elsif ($f =~ /hex/i) {
5541 return $self->AsHEXWKB;
5543 return $self->ExportToWkb($p->{byteorder});
5545 } elsif ($f =~ /gml/i) {
5546 return $self->ExportToGML($p->{options});
5547 } elsif ($f =~ /kml/i) {
5548 return $self->ExportToKML($p->{altitudemode});
5549 } elsif ($f =~ /json/i) {
5550 return $self->AsJSON;
5552 error(1, $f, map {$_=>1} qw/Text WKT ISO_WKT ISO_WKB HEX_WKB HEX_EWKB Binary GML KML JSON/);
5556 #** @method scalar AsBinary()
5558 # Export the geometry into WKB.
5559 # @sa Geo::OGR::Geometry::As
5560 # @return the geometry as WKB.
5565 #** @method scalar AsText()
5567 # Export the geometry into WKT.
5568 # @sa Geo::OGR::Geometry::As
5569 # @return the geometry as WKT.
5574 #** @method AssignSpatialReference($srs)
5576 # @param srs a Geo::OSR::SpatialReference object
5578 sub AssignSpatialReference {
5581 #** @method Geo::OGR::Geometry Boundary()
5583 # @note a.k.a. GetBoundary
5584 # @return the boundary of this geometry as a geometry
5590 #** @method Geo::OGR::Geometry Buffer($distance, $quadsecs = 30)
5594 # @return a new Geo::OGR::Geometry object
5599 #** @method Geo::OGR::Geometry BuildPolygonFromEdges($BestEffort = 0, $AutoClose = 0, $Tolerance = 0)
5601 # Attempt to create a polygon from a collection of lines or from a multilinestring.
5602 # @param BestEffort For future
5603 # @param AutoClose Assure the first and last points of rings are same.
5604 # @param Tolerance Snap distance.
5605 # @exception Several possibilities, some are reported, some are general errors.
5606 # @return a new Geo::OGR::Geometry object (Polygon)
5608 sub BuildPolygonFromEdges {
5611 #** @method list ByteOrders()
5612 # Package subroutine.
5613 # Same as Geo::OGR::ByteOrders
5616 return @BYTE_ORDER_TYPES;
5619 #** @method Geo::OGR::Geometry Centroid()
5621 # @return a new Geo::OGR::Geometry object
5627 #** @method Geo::OGR::Geometry Clone()
5629 # @return a new Geo::OGR::Geometry object
5634 #** @method CloseRings()
5640 #** @method Geo::OGR::Geometry Collect(@geometries)
5642 # Create a geometrycollection from this and possibly other geometries.
5643 # @param geometries [optional] More geometries to add to the collection.
5644 # @return a new Geo::OGR::Geometry object of type geometrycollection.
5649 #** @method scalar Contains($other)
5651 # @param other a Geo::OGR::Geometry object
5652 # @return true if this geometry contains the other geometry, false otherwise
5657 #** @method Geo::OGR::Geometry ConvexHull()
5659 # @return a new Geo::OGR::Geometry object
5664 #** @method scalar CoordinateDimension($dimension)
5666 # @param dimension [optional]
5669 sub CoordinateDimension {
5671 SetCoordinateDimension($self, $_[0]) if @_;
5672 GetCoordinateDimension($self) if defined wantarray;
5675 #** @method scalar Crosses($other)
5677 # @param other a Geo::OGR::Geometry object
5678 # @return true if this geometry crosses the other geometry, false otherwise
5683 #** @method DelaunayTriangulation()
5685 sub DelaunayTriangulation {
5688 #** @method Geo::OGR::Geometry Difference($other)
5690 # @param other a Geo::OGR::Geometry object
5691 # @return a new Geo::OGR::Geometry object
5696 #** @method scalar Disjoint($other)
5698 # @param other a Geo::OGR::Geometry object
5699 # @return true if this geometry is disjoint from the other geometry, false otherwise
5704 #** @method list Dissolve()
5706 # Dissolve a geometrycollection into separate geometries.
5707 # @return a list of new Geo::OGR::Geometry objects cloned from the collection.
5712 my $n = $self->GetGeometryCount;
5714 for my $i (0..$n-1) {
5715 push @c, $self->GetGeometryRef($i)->Clone;
5723 #** @method scalar Distance($other)
5725 # @param other a Geo::OGR::Geometry object
5726 # @return the distance to the other geometry
5731 #** @method Distance3D()
5738 # Clear geometry data, i.e., remove all points, or, for a point, set
5739 # the coordinate dimension as zero.
5744 #** @method scalar Equals($other)
5746 # @note a.k.a. Equal (deprecated)
5747 # @param other a Geo::OGR::Geometry object
5748 # @return true if this geometry is equivalent to the other geometry, false otherwise
5753 #** @method Extent()
5757 return Geo::GDAL::Extent->new($self->GetEnvelope);
5760 #** @method Feature()
5767 #** @method FlattenTo2D()
5773 #** @method Geo::OGR::Geometry ForceTo($type, ref options)
5775 # Attempt to make a geometry of type 'type' out of this geometry.
5776 # @param type target geometry type. One of Geo::OGR::GeometryTypes.
5777 # @param options not used currently.
5778 # @return a new Geo::OGR::Geometry object.
5783 $type = s2i(geometry_type => $type);
5785 $self = Geo::OGR::ForceTo($self, $type, @_);
5787 confess last_error() if $@;
5791 #** @method Geo::OGR::Geometry ForceToCollection(@geometries)
5793 # Create a geometrycollection from the geometry.
5794 # @param geometries [optional] More geometries to add to the collection.
5795 # @return a new Geo::OGR::Geometry object of type geometrycollection.
5797 sub ForceToCollection {
5798 my $self = Geo::OGR::Geometry->new(GeometryType => 'GeometryCollection');
5800 $self->AddGeometry($g);
5805 #** @method Geo::OGR::Geometry ForceToLineString()
5807 # Attempt to create a line string from this geometry.
5808 # @return a new Geo::OGR::Geometry object.
5810 sub ForceToLineString {
5812 return Geo::OGR::ForceToLineString($self);
5815 #** @method Geo::OGR::Geometry ForceToMultiLineString(@linestrings)
5817 # Attempt to create a multilinestring from the geometry, which must be a linestring.
5818 # @param linestrings [optional] More linestrings to add to the collection.
5819 # @return a new Geo::OGR::Geometry object of type multilinestring.
5821 sub ForceToMultiLineString {
5823 $self = Geo::OGR::ForceToMultiLineString($self);
5825 $self->AddGeometry($g);
5830 #** @method Geo::OGR::Geometry ForceToMultiPoint(@points)
5832 # Attempt to create a multipoint from the geometry, which must be a point.
5833 # @param points [optional] More points to add to the collection.
5834 # @return a new Geo::OGR::Geometry object of type multipoint.
5836 sub ForceToMultiPoint {
5838 $self = Geo::OGR::ForceToMultiPoint($self);
5840 $self->AddGeometry($g);
5845 #** @method Geo::OGR::Geometry ForceToMultiPolygon(@polygons)
5847 # Attempt to create a multipolygon from the geometry, which must be a polygon.
5848 # @param polygons [optional] More polygons to add to the collection.
5849 # @return a new Geo::OGR::Geometry object of type multipolygon.
5851 sub ForceToMultiPolygon {
5853 $self = Geo::OGR::ForceToMultiPolygon($self);
5855 $self->AddGeometry($g);
5860 #** @method Geo::OGR::Geometry ForceToPolygon()
5862 # Attempt to create a polygon from this geometry.
5863 # @exception None reported. If this method fails, just a copy is returned.
5864 # @return a new Geo::OGR::Geometry object.
5866 sub ForceToPolygon {
5869 #** @method scalar Geometry($n)
5871 # Return the n:th (note zero-based index) element in this geometry or
5872 # geometry in this collection.
5873 # @note a.k.a. GetGeometryRef
5874 # @param n index to the geometry, which is a part of this geometry
5875 # @return a new Geo::OGR::Geometry object whose data is a part of the
5876 # parent geometry (this geometry is kept alive while the returned
5882 #** @method scalar GeometryCount()
5884 # Return the number of elements in this geometry or geometries in this collection.
5885 # @note a.k.a. GetGeometryCount
5886 # @return an integer
5891 #** @method scalar GeometryType()
5894 # @note The deprecated method GetGeometryType returns the
5895 # type as an integer
5897 # @return the geometry type of this geometry (one of Geo::OGR::GeometryTypes).
5901 return i2s(geometry_type => $self->GetGeometryType);
5904 #** @method list GeometryTypes()
5905 # Package subroutine.
5906 # Same as Geo::OGR::GeometryTypes
5909 return @GEOMETRY_TYPES;
5912 #** @method scalar GetCoordinateDimension()
5914 # @return an integer
5916 sub GetCoordinateDimension {
5919 #** @method GetCurveGeometry()
5921 sub GetCurveGeometry {
5924 #** @method scalar GetDimension()
5926 # @return 0, 1, or 2
5931 #** @method list GetEnvelope()
5933 # @note In scalar context returns a reference to an anonymous array
5934 # containing the envelope.
5935 # @return the envelope ($minx, $maxx, $miny, $maxy)
5940 #** @method list GetEnvelope3D()
5942 # @note In scalar context returns a reference to an anonymous array
5943 # containing the envelope.
5944 # @return the 3-D envelope ($minx, $maxx, $miny, $maxy, $minz, $maxz)
5950 #** @method scalar GetGeometryRef($index)
5952 # @deprecated Use Geo::OGR::Geometry
5954 sub GetGeometryRef {
5955 my ($self, $i) = @_;
5956 my $ref = $self->_GetGeometryRef($i);
5961 #** @method GetLinearGeometry()
5963 sub GetLinearGeometry {
5971 #** @method list GetPoint($index = 0)
5974 # @return (x,y) or a list with more coordinates
5979 my $t = $self->GetGeometryType;
5980 my $has_z = HasZ($t);
5981 my $has_m = HasM($t);
5983 if (!$has_z && !$has_m) {
5984 $point = $self->GetPoint_2D($i);
5985 } elsif ($has_z && !$has_m) {
5986 $point = $self->GetPoint_3D($i);
5987 } elsif (!$has_z && $has_m) {
5988 $point = $self->GetPointZM($i);
5989 @$point = ($point->[0], $point->[1], $point->[3]);
5991 $point = $self->GetPointZM($i);
5993 return wantarray ? @$point : $point;
5996 #** @method scalar GetPointCount()
5998 # @return an integer
6003 #** @method GetPointZM()
6008 #** @method scalar GetPoint_2D($index = 0)
6011 # @return (x,y) or a list with more coordinates
6016 #** @method scalar GetPoint_3D($index = 0)
6019 # @return (x,y) or a list with more coordinates
6024 #** @method Geo::OSR::SpatialReference GetSpatialReference()
6026 # @return a new Geo::OSR::SpatialReference object
6028 sub GetSpatialReference {
6031 #** @method scalar GetX($index = 0)
6039 #** @method scalar GetY($index = 0)
6047 #** @method scalar GetZ($index = 0)
6055 #** @method HasCurveGeometry()
6057 sub HasCurveGeometry {
6060 #** @method Geo::OGR::Geometry Intersection($other)
6062 # @param other a Geo::OGR::Geometry object
6063 # @return a new Geo::OGR::Geometry object
6068 #** @method scalar Intersects($other)
6070 # @note a.k.a. Intersect (deprecated)
6071 # @param other a Geo::OGR::Geometry object
6072 # @return true if this geometry intersects with the other geometry, false otherwise
6082 #** @method scalar IsEmpty()
6084 # Test whether the geometry is empty (has no points, or, for a point,
6085 # has coordinate dimension of zero).
6091 #** @method IsMeasured()
6096 #** @method scalar IsRing()
6098 # Test if the geometry is a ring. Requires GEOS in GDAL.
6104 #** @method scalar IsSimple()
6106 # Test the simplicity of the geometry (OGC sense). Requires GEOS in GDAL.
6112 #** @method scalar IsValid()
6114 # Test the validity of the geometry (OGC sense). Requires GEOS in GDAL.
6120 #** @method scalar Length()
6122 # @return the length of the linestring
6127 #** @method Move($dx, $dy, $dz)
6129 # Move every point of the object as defined by the parameters.
6132 # @param dz [optional]
6137 #** @method scalar Overlaps($other)
6139 # @param other a Geo::OGR::Geometry object
6140 # @return true if this geometry overlaps the other geometry, false otherwise
6145 #** @method list Point($index, $x, $y, $z)
6147 # Get or set the point
6148 # @param index The index of the point. Optional (ignored if given) for
6149 # Point and Point25D geometries.
6150 # @param x [optional]
6151 # @param y [optional]
6152 # @param z [optional]
6159 my $t = $self->GetGeometryType;
6161 if (Flatten($t) == $Geo::OGR::wkbPoint) {
6162 my $has_z = HasZ($t);
6163 my $has_m = HasM($t);
6164 if (!$has_z && !$has_m) {
6167 } elsif ($has_z || $has_m) {
6175 $i = shift unless defined $i;
6176 $self->SetPoint($i, @_);
6178 return unless defined wantarray;
6179 my $point = $self->GetPoint;
6180 return wantarray ? @$point : $point;
6183 #** @method PointOnSurface()
6185 sub PointOnSurface {
6188 #** @method array reference Points(arrayref points)
6190 # Get or set the points of the geometry. The points (vertices) are
6191 # stored in obvious lists of lists. When setting, the geometry is
6192 # first emptied. The method uses internally either AddPoint_2D or
6193 # AddPoint_3D depending on the coordinate dimension of the input data.
6195 # @note The same structure may represent different geometries
6196 # depending on the actual geometry type of the object.
6198 # @param points [optional] A reference to an array. A point is a reference to an
6199 # array of numbers, a linestring or a ring is a reference to an array of points,
6200 # a polygon is a reference to an array of rings, etc.
6202 # @return A reference to an array.
6206 my $t = $self->GetGeometryType;
6207 my $has_z = HasZ($t);
6208 my $has_m = HasM($t);
6210 $postfix .= 'Z' if HasZ($t);
6211 $postfix .= 'M' if HasM($t);
6212 $t = i2s(geometry_type => Flatten($t));
6216 if ($t eq 'Unknown' or $t eq 'None' or $t eq 'GeometryCollection') {
6217 error("Can't set points of a geometry of type '$t'.");
6218 } elsif ($t eq 'Point') {
6219 # support both "Point" as a list of one point and one point
6220 if (ref($points->[0])) {
6221 $self->AddPoint(@{$points->[0]});
6223 $self->AddPoint(@$points);
6225 } elsif ($t eq 'LineString' or $t eq 'LinearRing' or $t eq 'CircularString') {
6226 for my $p (@$points) {
6227 $self->AddPoint(@$p);
6229 } elsif ($t eq 'Polygon') {
6230 for my $r (@$points) {
6231 my $ring = Geo::OGR::Geometry->new('LinearRing');
6232 $ring->Set3D(1) if $has_z;
6233 $ring->SetMeasured(1) if $has_m;
6235 $self->AddGeometryDirectly($ring);
6237 } elsif ($t eq 'MultiPoint') {
6238 for my $p (@$points) {
6239 my $point = Geo::OGR::Geometry->new('Point'.$postfix);
6241 $self->AddGeometryDirectly($point);
6243 } elsif ($t eq 'MultiLineString') {
6244 for my $l (@$points) {
6245 my $linestring = Geo::OGR::Geometry->new('LineString'.$postfix);
6246 $linestring->Points($l);
6247 $self->AddGeometryDirectly($linestring);
6249 } elsif ($t eq 'MultiPolygon') {
6250 for my $p (@$points) {
6251 my $polygon = Geo::OGR::Geometry->new('Polygon'.$postfix);
6252 $polygon->Points($p);
6253 $self->AddGeometryDirectly($polygon);
6257 return unless defined wantarray;
6258 $self->_GetPoints();
6261 #** @method Polygonize()
6266 #** @method RemoveGeometry()
6268 sub RemoveGeometry {
6271 #** @method Segmentize($MaxLength)
6273 # Modify the geometry such it has no segment longer than the given length.
6274 # @param MaxLength the given length
6284 #** @method SetCoordinateDimension($dimension)
6288 sub SetCoordinateDimension {
6291 #** @method SetMeasured()
6296 #** @method SetPoint($index, $x, $y, $z)
6298 # Set the data of a point or a line string. Note that the coordinate
6299 # dimension is automatically upgraded to 25D (3) if z is given.
6303 # @param z [optional]
6307 my $t = $self->GetGeometryType;
6308 my $has_z = HasZ($t);
6309 my $has_m = HasM($t);
6310 if (!$has_z && !$has_m) {
6311 $self->SetPoint_2D(@_[0..2]);
6312 } elsif ($has_z && !$has_m) {
6313 $self->SetPoint_3D(@_[0..3]);
6314 } elsif (!$has_z && $has_m) {
6315 $self->SetPointM(@_[0..3]);
6317 $self->SetPointZM(@_[0..4]);
6321 #** @method SetPointM()
6326 #** @method SetPointZM()
6331 #** @method SetPoint_2D($index, $x, $y)
6340 #** @method SetPoint_3D($index, $x, $y, $z)
6342 # Set the data of a point or a line string. Note that the coordinate
6343 # dimension is automatically upgraded to 25D (3).
6352 #** @method Geo::OGR::Geometry Simplify($Tolerance)
6354 # Simplify the geometry.
6355 # @param Tolerance the length tolerance for the simplification
6357 # @return a new Geo::OSR::Geometry object
6362 #** @method SimplifyPreserveTopology()
6364 sub SimplifyPreserveTopology {
6367 #** @method SwapXY()
6372 #** @method Geo::OGR::Geometry SymDifference($other)
6374 # Compute symmetric difference.
6375 # @note a.k.a. SymmetricDifference
6376 # @param other a Geo::OGR::Geometry object
6377 # @return a new Geo::OGR::Geometry object
6383 #** @method scalar Touches($other)
6385 # @param other a Geo::OGR::Geometry object
6386 # @return true if this geometry touches the other geometry, false otherwise
6391 #** @method Transform($trans)
6393 # @param trans a Geo::OSR::CoordinateTransformation object
6398 #** @method TransformTo($srs)
6400 # @param srs a Geo::OSR::SpatialReference object
6405 #** @method Geo::OGR::Geometry Union($other)
6407 # @param other a Geo::OGR::Geometry object
6408 # @return a new Geo::OGR::Geometry object
6413 #** @method Geo::OGR::Geometry UnionCascaded()
6415 # @return a new Geo::OGR::Geometry object
6426 #** @method scalar Within($other)
6428 # @param other a Geo::OGR::Geometry object
6429 # @return true if this geometry is within the other geometry, false otherwise
6434 #** @method scalar WkbSize()
6436 # @return an integer
6441 #** @method Geo::OGR::Geometry new(%params)
6443 # @param %params A named parameter, one of:
6444 # - \a GeometryType one the supported geometry types, see Geo::OGR::GeometryTypes.
6445 # - \a WKT a well known text string, which defines a geometry.
6446 # - \a WKB a well known binary string, which defines a geometry.
6447 # - \a HEXWKB WKB in hexadecimal.
6448 # - \a HEXEWKB PostGIS extended WKB.
6449 # - \a GML geometry written in Geographic Markup Language.
6450 # - \a GeoJSON geometry written in GeoJSON (JavaScript Object Notation for Geographic data).
6451 # - \a arc a reference to a list of values defining an arc: [CenterX,
6452 # CenterY, CenterZ, PrimaryRadius, SecondaryRadius, Rotation,
6453 # StartAngle, EndAngle, MaxAngleStepSizeDegrees] (see also Geo::OGR::Geometry::ApproximateArcAngles)
6454 # - \a Points An anonymous array as in method
6455 # Geo::OGR::Geometry::Points; Note: requires also GeometryType
6458 # @return a new Geo::OGR::Geometry object.
6463 if (@_ == 1 and ref($_[0]) eq 'HASH') {
6465 } elsif (@_ % 2 == 0) {
6468 ($param{GeometryType}) = @_;
6470 my $type = $param{GeometryType} // $param{Type} // $param{type};
6471 my $srs = $param{SRS} // $param{srs};
6472 my $wkt = $param{WKT} // $param{wkt};
6473 my $wkb = $param{WKB} // $param{wkb};
6474 my $hex = $param{HEXEWKB} // $param{HEX_EWKB} // $param{hexewkb} // $param{hex_ewkb};
6477 # EWKB contains SRID
6478 $srid = substr($hex, 10, 8);
6479 substr($hex, 10, 8) = '';
6481 $hex = $param{HEXWKB} // $param{HEX_WKB} // $param{hexwkb} // $param{hex_wkb};
6485 for (my $i = 0; $i < length($hex); $i+=2) {
6486 $wkb .= chr(hex(substr($hex,$i,2)));
6489 my $gml = $param{GML} // $param{gml};
6490 my $json = $param{GeoJSON} // $param{geojson} // $param{JSON} // $param{json};
6491 my $points = $param{Points} // $param{points};
6492 my $arc = $param{Arc} // $param{arc};
6495 $self = Geo::OGRc::CreateGeometryFromWkt($wkt, $srs);
6496 } elsif (defined $wkb) {
6497 $self = Geo::OGRc::CreateGeometryFromWkb($wkb, $srs);
6498 } elsif (defined $gml) {
6499 $self = Geo::OGRc::CreateGeometryFromGML($gml);
6500 } elsif (defined $json) {
6501 $self = Geo::OGRc::CreateGeometryFromJson($json);
6502 } elsif (defined $type) {
6503 $type = s2i(geometry_type => $type);
6504 $self = Geo::OGRc::new_Geometry($type); # flattens the type
6505 $self->Set3D(1) if HasZ($type);
6506 $self->SetMeasured(1) if HasM($type);
6507 } elsif (defined $arc) {
6508 $self = Geo::OGRc::ApproximateArcAngles(@$arc);
6510 error(1, undef, map {$_=>1} qw/GeometryType WKT WKB HEXEWKB HEXWKB GML GeoJSON Arc/);
6512 bless $self, $pkg if defined $self;
6513 $self->Points($points) if $points;
6517 #** @class Geo::OGR::Layer
6518 # @brief A collection of similar features.
6519 # @details A layer object is typically obtained with a data source object. A
6520 # layer has a data model (a schema), which is maintained in a
6521 # definition object, and a set of features, which contain data
6522 # according to the data model. The schema is typically set when the
6523 # layer is created or opened, but it may be altered somewhat with
6524 # methods Geo::OGR::Layer::CreateField,
6525 # Geo::OGR::Layer::AlterFieldDefn, and
6526 # Geo::OGR::Layer::DeleteField. Features and/or their data can be
6527 # read, inserted and deleted. Reading can be filtered. Layers can be
6528 # compared to each other with methods Clip, Erase, Identity,
6529 # Intersection, SymDifference, Union, and Update.
6530 # A layer may have metadata OLMD_FID64 => 'YES' if it holds features
6531 # with 64 bit FIDs. The metadata of a layer can be obtained with
6532 # GetMetadata method.
6534 package Geo::OGR::Layer;
6536 use base qw(Geo::GDAL::MajorObject Geo::OGR)
6538 #** @method AlterFieldDefn($name, %params)
6540 # @param field the name of the field to be altered.
6541 # @param params as in Geo::OGR::FieldDefn::new. Width and
6542 # Precision should be both or neither.
6543 # @note Only non-spatial fields can be altered.
6544 # @note Also the deprecated form AlterFieldDefn($field,
6545 # Geo::OGR::FieldDefn $Defn, $Flags) works.
6547 sub AlterFieldDefn {
6549 my $index = $self->GetLayerDefn->GetFieldIndex(shift // 0);
6550 my $param = @_ % 2 == 0 ? {@_} : shift;
6551 if (blessed($param) and $param->isa('Geo::OGR::FieldDefn')) {
6552 _AlterFieldDefn($self, $index, @_);
6554 my $definition = Geo::OGR::FieldDefn->new($param);
6556 $flags |= 1 if exists $param->{Name};
6557 $flags |= 2 if exists $param->{Type};
6558 $flags |= 4 if exists $param->{Width} or exists $param->{Precision};
6559 $flags |= 8 if exists $param->{Nullable};
6560 $flags |= 16 if exists $param->{Default};
6561 _AlterFieldDefn($self, $index, $definition, $flags);
6565 #** @method list Capabilities()
6567 # Both a package subroutine and an object method.
6568 # @return a list of capabilities. The object method returns a list of
6569 # the capabilities the layer has. The package subroutine returns a list of
6570 # all potential capabilities a layer may have. These are currently:
6571 # AlterFieldDefn, CreateField, CreateGeomField, CurveGeometries, DeleteFeature, DeleteField, FastFeatureCount, FastGetExtent, FastSetNextByIndex, FastSpatialFilter, IgnoreFields, MeasuredGeometries, RandomRead, RandomWrite, ReorderFields, SequentialWrite, StringsAsUTF8, and Transactions.
6575 # @cap = Geo::OGR::Layer::Capabilities(); # the package subroutine
6576 # @cap = $layer->Capabilities(); # the object method
6580 return @CAPABILITIES if @_ == 0;
6583 for my $cap (@CAPABILITIES) {
6584 push @cap, $cap if _TestCapability($self, $CAPABILITIES{$cap});
6589 #** @method Clip(Geo::OGR::Layer method, Geo::OGR::Layer result, hashref options, coderef callback, $callback_data)
6591 # Clip off areas that are not covered by the method layer. The schema
6592 # of the result layer can be set before calling this method, or is
6593 # initialized to to contain all fields from
6594 # this and method layer.
6595 # @param method method layer.
6596 # @param result result layer.
6597 # @param options a reference to an options hash.
6598 # @param callback [optional] a reference to a subroutine, which will
6599 # be called with parameters (number progress, string msg, callback_data)
6600 # @param callback_data [optional]
6605 #** @method CommitTransaction()
6608 sub CommitTransaction {
6611 #** @method CreateFeature()
6616 #** @method CreateField(%params)
6619 # @param params as in Geo::OGR::FieldDefn::new or
6620 # Geo::OGR::GeomFieldDefn::new, plus ApproxOK (whose default is true).
6624 my %defaults = ( ApproxOK => 1,
6628 } elsif (ref($_[0]) eq 'HASH') {
6630 } elsif (@_ % 2 == 0) {
6633 ($params{Defn}) = @_;
6635 for my $k (keys %defaults) {
6636 $params{$k} //= $defaults{$k};
6638 if (blessed($params{Defn}) and $params{Defn}->isa('Geo::OGR::FieldDefn')) {
6639 $self->_CreateField($params{Defn}, $params{ApproxOK});
6640 } elsif (blessed($_[0]) and $params{Defn}->isa('Geo::OGR::GeomFieldDefn')) {
6641 $self->CreateGeomField($params{Defn}, $params{ApproxOK});
6643 # if Name and Type are missing, assume Name => Type
6644 if (!(exists $params{Name} && exists $params{Type})) {
6645 for my $key (sort keys %params) {
6646 if (s_exists(field_type => $params{$key}) ||
6647 s_exists(geometry_type => $params{$key}))
6649 $params{Name} = $key;
6650 $params{Type} = $params{$key};
6651 delete $params{$key};
6656 my $a = $params{ApproxOK};
6657 delete $params{ApproxOK};
6658 if (exists $params{GeometryType}) {
6659 $params{Type} = $params{GeometryType};
6660 delete $params{GeometryType};
6662 if (s_exists(field_type => $params{Type})) {
6663 my $fd = Geo::OGR::FieldDefn->new(%params);
6664 _CreateField($self, $fd, $a);
6665 } elsif (s_exists(geometry_type => $params{Type})) {
6666 my $fd = Geo::OGR::GeomFieldDefn->new(%params);
6667 CreateGeomField($self, $fd, $a);
6668 } elsif ($params{Type} ) {
6669 error("Invalid field type: $params{Type}.")
6670 } elsif ($params{Name} ) {
6671 error("Missing type for field: $params{Name}.")
6673 error("Missing name and type for a field.")
6678 #** @method DataSource()
6683 #** @method Dataset()
6690 #** @method DeleteFeature($fid)
6692 # @param fid feature id
6697 #** @method DeleteField($field)
6699 # Delete an existing field from a layer.
6700 # @param field name (or index) of the field which is deleted
6701 # @note Only non-spatial fields can be deleted.
6704 my ($self, $field) = @_;
6705 my $index = $self->GetLayerDefn->GetFieldIndex($field // 0);
6706 _DeleteField($self, $index);
6709 #** @method Erase(Geo::OGR::Layer method, Geo::OGR::Layer result, hashref options, coderef callback, $callback_data)
6711 # The result layer contains features whose geometries represent areas
6712 # that are in the input layer but not in the method layer. The
6713 # features in the result layer have attributes from the input
6714 # layer. The schema of the result layer can be set by the user or, if
6715 # it is empty, is initialized to contain all fields in the input
6717 # @param method method layer.
6718 # @param result result layer.
6719 # @param options a reference to an options hash.
6720 # @param callback [optional] a reference to a subroutine, which will
6721 # be called with parameters (number progress, string msg, callback_data)
6722 # @param callback_data [optional]
6727 #** @method Geo::OGR::Feature Feature($f)
6730 # @param f [optional] feature id, a feature, a row, or a tuple
6732 # @note If the argument feature has a null FID (FID not set) the
6733 # feature is inserted into the layer as a new feature. If the FID is
6734 # non null, then the feature replaces the feature in the layer with
6737 # @return a new Geo::OGR::Feature object that represents the feature
6743 return $self->GetFeature($x) unless $x && ref $x;
6744 # Insert or Set depending on the FID
6746 if (ref $x eq 'ARRAY') {
6747 # FID is the first item in the array
6749 } elsif (ref $x eq 'HASH') {
6756 if (!defined $fid || $fid < 0) {
6757 $self->InsertFeature($x);
6759 $self->SetFeature($x);
6763 #** @method scalar FeatureCount($force = 1)
6765 # A.k.a GetFeatureCount
6772 #** @method Features()
6776 $self->ResetReading;
6778 return $self->GetNextFeature;
6782 #** @method ForFeatures($code, $in_place)
6784 # @note experimental, the syntax may change
6786 # Call code for all features. This is a simple wrapper for
6787 # ResetReading and while(GetNextFeature).
6791 # $layer->ForFeatures(sub {my $f = shift; $self->DeleteFeature($f->FID)}); # empties the layer
6794 # @param code a reference to a subroutine, which is called with each
6795 # feature as an argument
6796 # @param in_place if set to true, the feature is stored back to the
6802 my $in_place = shift;
6803 $self->ResetReading;
6804 while (my $f = $self->GetNextFeature) {
6807 $self->SetFeature($f) if $in_place;
6811 #** @method ForGeometries($code, $in_place)
6813 # @note experimental, the syntax may change
6815 # Call code for all geometries. This is a simple wrapper for
6816 # ResetReading and while(GetNextFeature).
6821 # $layer->ForGeometries(sub {my $g = shift; $area += $g->Area}); # computes the total area
6824 # @param code a reference to a subroutine, which is called with each
6825 # geometry as an argument
6826 # @param in_place if set to true, the geometry is stored back to the
6832 my $in_place = shift;
6833 $self->ResetReading;
6834 while (my $f = $self->GetNextFeature) {
6835 my $g = $f->Geometry();
6839 $self->SetFeature($f);
6844 #** @method Geometries()
6848 $self->ResetReading;
6850 my $f = $self->GetNextFeature;
6852 return $f->Geometry;
6856 #** @method scalar GeometryType($field)
6858 # @param field the name or index of the spatial field.
6859 # @return the geometry type of the spatial field.
6863 my $d = $self->GetDefn;
6864 my $field = $d->GetGeomFieldIndex(shift // 0);
6865 my $fd = $d->_GetGeomFieldDefn($field);
6866 return $fd->Type if $fd;
6869 #** @method Geo::OGR::DataSource GetDataSource()
6871 # @return the data source object to which this layer object belongs to.
6878 #** @method Geo::OGR::FeatureDefn GetDefn()
6880 # A.k.a GetLayerDefn.
6881 # @return a Geo::OGR::FeatureDefn object.
6885 my $defn = $self->GetLayerDefn;
6889 #** @method list GetExtent($force = 1)
6891 # @param force compute the extent even if it is expensive
6892 # @note In scalar context returns a reference to an anonymous array
6893 # containing the extent.
6894 # @return the extent ($minx, $maxx, $miny, $maxy)
6896 # @return the extent = ($minx, $maxx, $miny, $maxy) as a listref
6901 #** @method scalar GetFIDColumn()
6903 # @return the name of the underlying database column being used as the
6904 # FID column, or "" if not supported.
6909 #** @method Geo::OGR::Feature GetFeature($fid)
6911 # @param fid feature id
6912 # @return a new Geo::OGR::Feature object that represents the feature in the layer.
6915 my ($self, $fid) = @_;
6917 my $f = $self->_GetFeature($fid);
6918 error(2, "FID=$fid", '"Feature') unless ref $f eq 'Geo::OGR::Feature';
6922 #** @method GetFeatureCount()
6924 sub GetFeatureCount {
6927 #** @method scalar GetFeaturesRead()
6931 sub GetFeaturesRead {
6934 #** @method scalar GetFieldDefn($name)
6936 # Get the definition of a field.
6937 # @param name the name of the field.
6938 # @return a Geo::OGR::FieldDefn object.
6942 my $d = $self->GetDefn;
6943 my $field = $d->GetFieldIndex(shift // 0);
6944 return $d->_GetFieldDefn($field);
6947 #** @method list GetFieldNames()
6949 # @return a list of the names of the fields in this layer. The
6950 # non-geometry field names are first in the list and then the geometry
6955 my $d = $self->GetDefn;
6957 for (my $i = 0; $i < $d->GetFieldCount; $i++) {
6958 push @ret, $d->GetFieldDefn($i)->Name();
6960 for (my $i = 0; $i < $d->GetGeomFieldCount; $i++) {
6961 push @ret, $d->GetGeomFieldDefn($i)->Name();
6966 #** @method scalar GetGeomFieldDefn($name)
6968 # Get the definition of a spatial field.
6969 # @param name the name of the spatial field.
6970 # @return a Geo::OGR::GeomFieldDefn object.
6972 sub GetGeomFieldDefn {
6974 my $d = $self->GetDefn;
6975 my $field = $d->GetGeomFieldIndex(shift // 0);
6976 return $d->_GetGeomFieldDefn($field);
6979 #** @method scalar GetName()
6981 # @return the name of the layer.
6986 #** @method Geo::OGR::Feature GetNextFeature()
6988 # @return iteratively Geo::OGR::Feature objects from the layer. The
6989 # iteration obeys the spatial and the attribute filter.
6991 sub GetNextFeature {
6994 #** @method hash reference GetSchema()
6996 # @brief Get the schema of this layer.
6997 # @note The schema of a layer cannot be set with this method. If you
6998 # have a Geo::OGR::FeatureDefn object before creating the layer, use
6999 # its schema in the Geo::OGR::CreateLayer method.
7000 # @return the schema of this layer, as in Geo::OGR::FeatureDefn::Schema.
7004 carp "Schema of a layer should not be set directly." if @_;
7005 if (@_ and @_ % 2 == 0) {
7007 if ($schema{Fields}) {
7008 for my $field (@{$schema{Fields}}) {
7009 $self->CreateField($field);
7013 return $self->GetDefn->Schema;
7016 #** @method Geo::OGR::Geometry GetSpatialFilter()
7018 # @return a new Geo::OGR::Geometry object
7020 sub GetSpatialFilter {
7023 #** @method GetStyleTable()
7028 #** @method Identity(Geo::OGR::Layer method, Geo::OGR::Layer result, hashref options, coderef callback, $callback_data)
7030 # The result layer contains features whose geometries represent areas
7031 # that are in the input layer. The features in the result layer have
7032 # attributes from both input and method layers. The schema of the
7033 # result layer can be set by the user or, if it is empty, is
7034 # initialized to contain all fields in input and method layers.
7035 # @param method method layer.
7036 # @param result result layer.
7037 # @param options a reference to an options hash.
7038 # @param callback [optional] a reference to a subroutine, which will
7039 # be called with parameters (number progress, string msg, callback_data)
7040 # @param callback_data [optional]
7045 #** @method InsertFeature($feature)
7047 # Creates a new feature which has the schema of the layer and
7048 # initializes it with data from the argument. Then inserts the feature
7049 # into the layer (using CreateFeature). Uses Geo::OGR::Feature::Row or
7050 # Geo::OGR::Feature::Tuple.
7051 # @param feature a Geo::OGR::Feature object or reference to feature
7052 # data in a hash (as in Geo::OGR::Feature::Row) or in an array (as in
7053 # Geo::OGR::Feature::Tuple)
7054 # @return the new feature.
7058 my $feature = shift;
7059 error("Usage: \$feature->InsertFeature(reference to a hash or array).") unless ref($feature);
7060 my $new = Geo::OGR::Feature->new(Schema => $self, Values => $feature);
7061 $self->CreateFeature($new);
7062 return unless defined wantarray;
7066 #** @method Intersection(Geo::OGR::Layer method, Geo::OGR::Layer result, hashref options, coderef callback, $callback_data)
7068 # The result layer contains features whose geometries represent areas
7069 # that are common between features in the input layer and in the
7070 # method layer. The schema of the result layer can be set before
7071 # calling this method, or is initialized to contain all fields from
7072 # this and method layer.
7073 # @param method method layer.
7074 # @param result result layer.
7075 # @param options a reference to an options hash.
7076 # @param callback [optional] a reference to a subroutine, which will
7077 # be called with parameters (number progress, string msg, callback_data)
7078 # @param callback_data [optional]
7083 #** @method ReorderField()
7088 #** @method ReorderFields()
7093 #** @method ResetReading()
7095 # Initialize the layer object for iterative reading.
7100 #** @method RollbackTransaction()
7103 sub RollbackTransaction {
7106 #** @method hash reference Row(%row)
7108 # Get and/or set the data of a feature that has the supplied feature
7109 # id (the next feature obtained with GetNextFeature is used if feature
7110 # id is not given). Calls Geo::OGR::Feature::Row.
7111 # @param row [optional] feature data
7112 # @return a reference to feature data in a hash
7116 my $update = @_ > 0;
7118 my $feature = defined $row{FID} ? $self->GetFeature($row{FID}) : $self->GetNextFeature;
7119 return unless $feature;
7121 if (defined wantarray) {
7122 $ret = $feature->Row(@_);
7126 $self->SetFeature($feature) if $update;
7127 return unless defined wantarray;
7131 #** @method SetAttributeFilter($filter_string)
7133 # Set or clear the attribute filter.
7134 # @param filter_string a SQL WHERE clause or undef to clear the
7137 sub SetAttributeFilter {
7140 #** @method SetFeature($feature)
7142 # @note The feature should have the same schema as the layer.
7144 # Replaces a feature in the layer based on the given feature's
7145 # id. Requires RandomWrite capability.
7146 # @param feature a Geo::OGR::Feature object
7151 #** @method SetIgnoredFields(@fields)
7153 # @param fields a list of field names
7155 sub SetIgnoredFields {
7158 #** @method SetNextByIndex($new_index)
7160 # @param new_index the index to which set the read cursor in the
7163 sub SetNextByIndex {
7166 #** @method SetSpatialFilter($filter)
7168 # @param filter [optional] a Geo::OGR::Geometry object. If not given,
7169 # removes the filter if there is one.
7171 sub SetSpatialFilter {
7174 #** @method SetSpatialFilterRect($minx, $miny, $maxx, $maxy)
7181 sub SetSpatialFilterRect {
7184 #** @method SetStyleTable()
7189 #** @method Geo::OGR::Geometry SpatialFilter(@filter)
7191 # @param filter [optional] a Geo::OGR::Geometry object or a string. An
7192 # undefined value removes the filter if there is one.
7193 # @return a new Geo::OGR::Geometry object
7194 # @param filter [optional] a rectangle ($minx, $miny, $maxx, $maxy).
7195 # @return a new Geo::OGR::Geometry object
7199 $self->SetSpatialFilter($_[0]) if @_ == 1;
7200 $self->SetSpatialFilterRect(@_) if @_ == 4;
7201 return unless defined wantarray;
7202 $self->GetSpatialFilter;
7205 #** @method Geo::OSR::SpatialReference SpatialReference($name, Geo::OSR::SpatialReference sr)
7207 # @note A.k.a GetSpatialRef.
7208 # Get or set the projection of a spatial field of this layer. Gets or
7209 # sets the projection of the first field if no field name is given.
7210 # @param name [optional] a name of a spatial field in this layer.
7211 # @param sr [optional] a Geo::OSR::SpatialReference object,
7212 # which replaces the existing projection.
7213 # @return a Geo::OSR::SpatialReference object, which represents the
7214 # projection in the given spatial field.
7216 sub SpatialReference {
7218 my $d = $self->GetDefn;
7219 my $field = @_ == 2 ? $d->GetGeomFieldIndex(shift // 0) : 0;
7221 my $d2 = $d->_GetGeomFieldDefn($field);
7222 $d2->SpatialReference($sr) if defined $sr;
7223 return $d2->SpatialReference() if defined wantarray;
7226 #** @method StartTransaction()
7229 sub StartTransaction {
7232 #** @method SymDifference(Geo::OGR::Layer method, Geo::OGR::Layer result, hashref options, coderef callback, $callback_data)
7234 # The result layer contains features whose geometries represent areas
7235 # that are in either in the input layer or in the method layer but not
7236 # in both. The features in the result layer have attributes from both
7237 # input and method layers. For features which represent areas that are
7238 # only in the input or in the method layer the respective attributes
7239 # have undefined values. The schema of the result layer can be set by
7240 # the user or, if it is empty, is initialized to contain all fields in
7241 # the input and method layers.
7242 # @param method method layer.
7243 # @param result result layer.
7244 # @param options a reference to an options hash.
7245 # @param callback [optional] a reference to a subroutine, which will
7246 # be called with parameters (number progress, string msg, callback_data)
7247 # @param callback_data [optional]
7252 #** @method SyncToDisk()
7258 #** @method scalar TestCapability($cap)
7260 # @param cap A capability string.
7261 # @return a boolean value indicating whether the layer has the
7262 # specified capability.
7264 sub TestCapability {
7265 my($self, $cap) = @_;
7266 return _TestCapability($self, $CAPABILITIES{$cap});
7269 #** @method list Tuple(@tuple)
7271 # Get and/set the data of a feature that has the supplied feature id
7272 # (the next feature obtained with GetNextFeature is used if feature id
7273 # is not given). The expected data in the tuple is: ([feature id,]
7274 # non-spatial fields, spatial fields). Calls Geo::OGR::Feature::Tuple.
7275 # @param tuple [optional] feature data
7276 # @note The schema of the tuple needs to be the same as that of the
7278 # @return a reference to feature data in an array
7283 my $feature = defined $FID ? $self->GetFeature($FID) : $self->GetNextFeature;
7284 return unless $feature;
7286 unshift @_, $feature->GetFID if $set;
7288 if (defined wantarray) {
7289 @ret = $feature->Tuple(@_);
7291 $feature->Tuple(@_);
7293 $self->SetFeature($feature) if $set;
7294 return unless defined wantarray;
7298 #** @method Union(Geo::OGR::Layer method, Geo::OGR::Layer result, hashref options, coderef callback, $callback_data)
7300 # The result layer contains features whose geometries represent areas
7301 # that are in either in the input layer or in the method layer. The
7302 # schema of the result layer can be set before calling this method, or
7303 # is initialized to contain all fields from this and method layer.
7304 # @param method method layer.
7305 # @param result result layer.
7306 # @param options a reference to an options hash.
7307 # @param callback [optional] a reference to a subroutine, which will
7308 # be called with parameters (number progress, string msg, callback_data)
7309 # @param callback_data [optional]
7314 #** @method Update(Geo::OGR::Layer method, Geo::OGR::Layer result, hashref options, coderef callback, $callback_data)
7316 # The result layer contains features whose geometries represent areas
7317 # that are either in the input layer or in the method layer. The
7318 # features in the result layer have areas of the features of the
7319 # method layer or those ares of the features of the input layer that
7320 # are not covered by the method layer. The features of the result
7321 # layer get their attributes from the input layer. The schema of the
7322 # result layer can be set by the user or, if it is empty, is
7323 # initialized to contain all fields in the input layer.
7324 # @param method method layer.
7325 # @param result result layer.
7326 # @param options a reference to an options hash.
7327 # @param callback [optional] a reference to a subroutine, which will
7328 # be called with parameters (number progress, string msg, callback_data)
7329 # @param callback_data [optional]
7334 #** @class Geo::OGR::StyleTable
7336 package Geo::OGR::StyleTable;
7338 use base qw(Geo::OGR)
7340 #** @method AddStyle()
7350 #** @method GetLastStyleName()
7352 sub GetLastStyleName {
7355 #** @method GetNextStyle()
7360 #** @method LoadStyleTable()
7362 sub LoadStyleTable {
7365 #** @method ResetStyleStringReading()
7367 sub ResetStyleStringReading {
7370 #** @method SaveStyleTable()
7372 sub SaveStyleTable {
7379 my $self = Geo::OGRc::new_StyleTable(@_);
7380 bless $self, $pkg if defined($self);
7384 # @brief Base class for projection related classes.
7389 #** @method list AngularUnits()
7390 # Package subroutine.
7391 # @return list of known angular units.
7394 return keys %ANGULAR_UNITS;
7397 #** @method CreateCoordinateTransformation()
7399 sub CreateCoordinateTransformation {
7402 #** @method list Datums()
7403 # Package subroutine.
7404 # @return list of known datums.
7407 return keys %DATUMS;
7410 #** @method list GetProjectionMethodParamInfo($projection, $parameter)
7411 # Package subroutine.
7412 # @param projection one of Geo::OSR::Projections
7413 # @param parameter one of Geo::OSR::Parameters
7414 # @return a list ($user_friendly_name, $type, $default_value).
7416 sub GetProjectionMethodParamInfo {
7419 #** @method list GetProjectionMethodParameterList($projection)
7420 # Package subroutine.
7421 # @param projection one of Geo::OSR::Projections
7422 # @return a list (arrayref parameters, $projection_name).
7424 sub GetProjectionMethodParameterList {
7427 #** @method array reference GetProjectionMethods()
7428 # Package subroutine.
7429 # @deprecated Use Geo::OSR::Projections.
7431 # @return reference to an array of possible projection methods.
7433 sub GetProjectionMethods {
7436 #** @method scalar GetUserInputAsWKT($name)
7437 # Package subroutine.
7438 # @param name the user input
7439 # @return a WKT string.
7441 sub GetUserInputAsWKT {
7444 #** @method scalar GetWellKnownGeogCSAsWKT($name)
7445 # Package subroutine.
7446 # @brief Get well known geographic coordinate system as WKT
7447 # @param name a well known name
7448 # @return a WKT string.
7450 sub GetWellKnownGeogCSAsWKT {
7453 #** @method list LinearUnits()
7454 # Package subroutine.
7455 # @return list of known linear units.
7458 return keys %LINEAR_UNITS;
7461 #** @method OAO_Down()
7466 #** @method OAO_East()
7471 #** @method OAO_North()
7476 #** @method OAO_Other()
7481 #** @method OAO_South()
7486 #** @method OAO_Up()
7491 #** @method OAO_West()
7496 #** @method list Parameters()
7497 # Package subroutine.
7498 # @return list of known projection parameters.
7501 return keys %PARAMETERS;
7504 #** @method list Projections()
7505 # Package subroutine.
7506 # @return list of known projections.
7509 return keys %PROJECTIONS;
7512 #** @method SRS_PM_GREENWICH()
7514 sub SRS_PM_GREENWICH {
7517 #** @method SRS_WGS84_INVFLATTENING()
7519 sub SRS_WGS84_INVFLATTENING {
7522 #** @method SRS_WGS84_SEMIMAJOR()
7524 sub SRS_WGS84_SEMIMAJOR {
7527 #** @method SRS_WKT_WGS84()
7532 #** @class Geo::OSR::CoordinateTransformation
7533 # @brief An object for transforming from one projection to another.
7536 package Geo::OSR::CoordinateTransformation;
7538 use base qw(Geo::OSR)
7540 #** @method array reference TransformPoint($x, $y, $z)
7544 # @param z [optional]
7545 # @return arrayref = [$x, $y, $z]
7547 sub TransformPoint {
7550 #** @method TransformPoints(arrayref points)
7552 # @param points [in/out] a reference to a list of points (line string
7553 # or ring) that is modified in-place. A list of points is: ([x, y, z],
7554 # [x, y, z], ...), where z is optional. Supports also lists of line
7555 # strings and polygons.
7557 sub TransformPoints {
7558 my($self, $points) = @_;
7559 _TransformPoints($self, $points), return unless ref($points->[0]->[0]);
7560 for my $p (@$points) {
7561 TransformPoints($self, $p);
7565 # This file was automatically generated by SWIG (http://www.swig.org).
7568 # Do not make changes to this file unless you know what you are doing--modify
7569 # the SWIG interface file instead.
7572 #** @method Geo::OSR::CoordinateTransformation new($src, $dst)
7574 # @param src a Geo::OSR::SpatialReference object
7575 # @param dst a Geo::OSR::SpatialReference object
7576 # @return a new Geo::OSR::CoordinateTransformation object
7580 my $self = Geo::OSRc::new_CoordinateTransformation(@_);
7581 bless $self, $pkg if defined($self);
7584 #** @class Geo::OSR::SpatialReference
7585 # @brief A spatial reference system.
7586 # @details <a href="http://www.gdal.org/classOGRSpatialReference.html">Documentation
7587 # of the underlying C++ class at www.gdal.org</a>
7589 package Geo::OSR::SpatialReference;
7591 use base qw(Geo::OSR)
7598 #** @method AutoIdentifyEPSG()
7600 # Set EPSG authority info if possible.
7602 sub AutoIdentifyEPSG {
7605 #** @method Geo::OSR::SpatialReference Clone()
7607 # Make a duplicate of this SpatialReference object.
7608 # @return a new Geo::OSR::SpatialReference object
7613 #** @method Geo::OSR::SpatialReference CloneGeogCS()
7615 # Make a duplicate of the GEOGCS node of this SpatialReference object.
7616 # @return a new Geo::OSR::SpatialReference object
7621 #** @method ConvertToOtherProjection()
7623 sub ConvertToOtherProjection {
7626 #** @method CopyGeogCSFrom($rhs)
7628 # @param rhs Geo::OSR::SpatialReference
7630 sub CopyGeogCSFrom {
7633 #** @method EPSGTreatsAsLatLong()
7635 # Returns TRUE if EPSG feels this geographic coordinate system should be treated as having lat/long coordinate ordering.
7637 sub EPSGTreatsAsLatLong {
7640 #** @method EPSGTreatsAsNorthingEasting()
7642 sub EPSGTreatsAsNorthingEasting {
7645 #** @method Export($format)
7647 # Export the spatial reference to a selected format.
7650 # @param format One of the following. The return value is explained
7651 # after the format. Other arguments are explained in parenthesis.
7652 # - WKT (Text): Well Known Text string
7653 # - PrettyWKT: Well Known Text string nicely formatted (simplify)
7654 # - Proj4: PROJ.4 string
7655 # - PCI: a list: ($proj_string, $units, [$parms1, ...])
7656 # - USGS: a list: ($code, $zone, [$parms1, ...], $datum)
7657 # - GML (XML): GML based string (dialect)
7658 # - MapInfoCS (MICoordSys): MapInfo style co-ordinate system definition
7660 # @note The named parameter syntax also works and is needed is those
7661 # cases when other arguments need or may be given. The format should
7662 # be given using key as, 'to' or 'format'.
7664 # @note ExportTo* and AsText methods also exist but are not documented here.
7666 # @return a scalar or a list depending on the export format
7671 $format = pop if @_ == 1;
7673 $format //= $params{to} //= $params{format} //= $params{as} //= '';
7674 my $simplify = $params{simplify} // 0;
7675 my $dialect = $params{dialect} // '';
7677 WKT => sub { return ExportToWkt($self) },
7678 Text => sub { return ExportToWkt($self) },
7679 PrettyWKT => sub { return ExportToPrettyWkt($self, $simplify) },
7680 Proj4 => sub { return ExportToProj4($self) },
7681 PCI => sub { return ExportToPCI($self) },
7682 USGS => sub { return ExportToUSGS($self) },
7683 GML => sub { return ExportToXML($self, $dialect) },
7684 XML => sub { return ExportToXML($self, $dialect) },
7685 MICoordSys => sub { return ExportToMICoordSys() },
7686 MapInfoCS => sub { return ExportToMICoordSys() },
7688 error(1, $format, \%converters) unless $converters{$format};
7689 return $converters{$format}->();
7698 #** @method FixupOrdering()
7704 #** @method scalar GetAngularUnits()
7708 sub GetAngularUnits {
7711 #** @method GetAngularUnitsName()
7713 sub GetAngularUnitsName {
7716 #** @method scalar GetAttrValue($name, $child = 0)
7725 #** @method scalar GetAuthorityCode($target_key)
7730 sub GetAuthorityCode {
7733 #** @method scalar GetAuthorityName($target_key)
7738 sub GetAuthorityName {
7741 #** @method GetAxisName()
7746 #** @method GetAxisOrientation()
7748 sub GetAxisOrientation {
7751 #** @method GetInvFlattening()
7754 sub GetInvFlattening {
7757 #** @method scalar GetLinearUnits()
7761 sub GetLinearUnits {
7764 #** @method scalar GetLinearUnitsName()
7768 sub GetLinearUnitsName {
7771 #** @method scalar GetNormProjParm($name, $default_val = 0.0)
7774 # @param default_val
7777 sub GetNormProjParm {
7780 #** @method scalar GetProjParm($name, $default_val = 0.0)
7783 # @param default_val
7789 #** @method GetSemiMajor()
7795 #** @method GetSemiMinor()
7801 #** @method GetTOWGS84()
7803 # @return array = ($p1, $p2, $p3, $p4, $p5, $p6, $p7)
7808 #** @method GetTargetLinearUnits()
7810 sub GetTargetLinearUnits {
7813 #** @method GetUTMZone()
7815 # Get UTM zone information.
7816 # @return The UTM zone (integer). In scalar context the returned value
7817 # is negative for southern hemisphere zones. In list context returns
7818 # two values ($zone, $north), where $zone is always non-negative and
7819 # $north is true or false.
7823 my $zone = _GetUTMZone($self);
7830 return ($zone, $north);
7836 #** @method ImportFromOzi()
7841 #** @method scalar IsCompound()
7848 #** @method scalar IsGeocentric()
7855 #** @method scalar IsGeographic()
7862 #** @method scalar IsLocal()
7869 #** @method scalar IsProjected()
7876 #** @method scalar IsSame($rs)
7878 # @param rs a Geo::OSR::SpatialReference object
7884 #** @method scalar IsSameGeogCS($rs)
7886 # @param rs a Geo::OSR::SpatialReference object
7892 #** @method scalar IsSameVertCS($rs)
7894 # @param rs a Geo::OSR::SpatialReference object
7900 #** @method scalar IsVertical()
7907 #** @method MorphFromESRI()
7913 #** @method MorphToESRI()
7919 #** @method Set(%params)
7921 # Set a parameter or parameters in the spatial reference object.
7922 # @param params Named parameters. Recognized keys and respective
7923 # values are the following.
7924 # - Authority: authority name (give also TargetKey, Node and Code)
7926 # - Node: partial or complete path to the target node (Node and Value together sets an attribute value)
7927 # - Code: code for value with an authority
7928 # - Value: value to be assigned to a node, a projection parameter or an object
7929 # - AngularUnits: angular units for the geographic coordinate system (give also Value) (one of Geo::OSR::LinearUnits)
7930 # - LinearUnits: linear units for the target node or the object (give also Value and optionally Node) (one of Geo::OSR::LinearUnits)
7931 # - Parameter: projection parameter to set (give also Value and Normalized) (one of Geo::OSR::Parameters)
7932 # - Normalized: set to true to indicate that the Value argument is in "normalized" form
7933 # - Name: a well known name of a geographic coordinate system (e.g. WGS84)
7934 # - GuessFrom: arbitrary text that specifies a projection ("user input")
7935 # - LOCAL_CS: name of a local coordinate system
7936 # - GeocentricCS: name of a geocentric coordinate system
7937 # - VerticalCS: name of a vertical coordinate system (give also Datum and optionally VertDatumType [default is 2005])
7938 # - Datum: a known (OGC or EPSG) name (or(?) one of Geo::OSR::Datums)
7939 # - 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
7940 # - Parameters: a reference to a list containing the coordinate system or projection parameters
7941 # - Zone: zone for setting up UTM or State Plane coordinate systems (State Plane zone in USGS numbering scheme)
7942 # - North: set false for southern hemisphere
7943 # - NAD83: set false if the NAD27 zone definition should be used instead of NAD83
7944 # - UnitName: to override the legal definition for a zone
7945 # - UnitConversionFactor: to override the legal definition for a zone
7946 # - Spheroid: user visible name
7947 # - HorizontalCS: Horizontal coordinate system name
7948 # - Projection: name of a projection, one of Geo::OSR::Projections (give also optionally Parameters and Variant)
7950 # @note Numerous Set* methods also exist but are not documented here.
7953 my($self, %params) = @_;
7954 if (exists $params{Authority} and exists $params{TargetKey} and exists $params{Node} and exists $params{Code}) {
7955 SetAuthority($self, $params{TargetKey}, $params{Authority}, $params{Code});
7956 } elsif (exists $params{Node} and exists $params{Value}) {
7957 SetAttrValue($self, $params{Node}, $params{Value});
7958 } elsif (exists $params{AngularUnits} and exists $params{Value}) {
7959 SetAngularUnits($self, $params{AngularUnits}, $params{Value});
7960 } elsif (exists $params{LinearUnits} and exists $params{Node} and exists $params{Value}) {
7961 SetTargetLinearUnits($self, $params{Node}, $params{LinearUnits}, $params{Value});
7962 } elsif (exists $params{LinearUnits} and exists $params{Value}) {
7963 SetLinearUnitsAndUpdateParameters($self, $params{LinearUnits}, $params{Value});
7964 } elsif ($params{Parameter} and exists $params{Value}) {
7965 error(1, $params{Parameter}, \%Geo::OSR::PARAMETERS) unless exists $Geo::OSR::PARAMETERS{$params{Parameter}};
7966 $params{Normalized} ?
7967 SetNormProjParm($self, $params{Parameter}, $params{Value}) :
7968 SetProjParm($self, $params{Parameter}, $params{Value});
7969 } elsif (exists $params{Name}) {
7970 SetWellKnownGeogCS($self, $params{Name});
7971 } elsif (exists $params{GuessFrom}) {
7972 SetFromUserInput($self, $params{GuessFrom});
7973 } elsif (exists $params{LOCAL_CS}) {
7974 SetLocalCS($self, $params{LOCAL_CS});
7975 } elsif (exists $params{GeocentricCS}) {
7976 SetGeocCS($self, $params{GeocentricCS});
7977 } elsif (exists $params{VerticalCS} and $params{Datum}) {
7978 my $type = $params{VertDatumType} || 2005;
7979 SetVertCS($self, $params{VerticalCS}, $params{Datum}, $type);
7980 } elsif (exists $params{CoordinateSystem}) {
7981 my @parameters = ();
7982 @parameters = @{$params{Parameters}} if ref($params{Parameters});
7983 if ($params{CoordinateSystem} eq 'State Plane' and exists $params{Zone}) {
7984 my $NAD83 = exists $params{NAD83} ? $params{NAD83} : 1;
7985 my $name = exists $params{UnitName} ? $params{UnitName} : undef;
7986 my $c = exists $params{UnitConversionFactor} ? $params{UnitConversionFactor} : 0.0;
7987 SetStatePlane($self, $params{Zone}, $NAD83, $name, $c);
7988 } elsif ($params{CoordinateSystem} eq 'UTM' and exists $params{Zone} and exists $params{North}) {
7989 my $north = exists $params{North} ? $params{North} : 1;
7990 SetUTM($self, $params{Zone}, $north);
7991 } elsif ($params{CoordinateSystem} eq 'WGS') {
7992 SetTOWGS84($self, @parameters);
7993 } elsif ($params{CoordinateSystem} and $params{Datum} and $params{Spheroid}) {
7994 SetGeogCS($self, $params{CoordinateSystem}, $params{Datum}, $params{Spheroid}, @parameters);
7995 } elsif ($params{CoordinateSystem} and $params{HorizontalCS} and $params{VerticalCS}) {
7996 SetCompoundCS($self, $params{CoordinateSystem}, $params{HorizontalCS}, $params{VerticalCS});
7998 SetProjCS($self, $params{CoordinateSystem});
8000 } elsif (exists $params{Projection}) {
8001 error(1, $params{Projection}, \%Geo::OSR::PROJECTIONS) unless exists $Geo::OSR::PROJECTIONS{$params{Projection}};
8002 my @parameters = ();
8003 @parameters = @{$params{Parameters}} if ref($params{Parameters});
8004 if ($params{Projection} eq 'Albers_Conic_Equal_Area') {
8005 SetACEA($self, @parameters);
8006 } elsif ($params{Projection} eq 'Azimuthal_Equidistant') {
8007 SetAE($self, @parameters);
8008 } elsif ($params{Projection} eq 'Bonne') {
8009 SetBonne($self, @parameters);
8010 } elsif ($params{Projection} eq 'Cylindrical_Equal_Area') {
8011 SetCEA($self, @parameters);
8012 } elsif ($params{Projection} eq 'Cassini_Soldner') {
8013 SetCS($self, @parameters);
8014 } elsif ($params{Projection} eq 'Equidistant_Conic') {
8015 SetEC($self, @parameters);
8016 # Eckert_I, Eckert_II, Eckert_III, Eckert_V ?
8017 } elsif ($params{Projection} eq 'Eckert_IV') {
8018 SetEckertIV($self, @parameters);
8019 } elsif ($params{Projection} eq 'Eckert_VI') {
8020 SetEckertVI($self, @parameters);
8021 } elsif ($params{Projection} eq 'Equirectangular') {
8023 SetEquirectangular($self, @parameters) :
8024 SetEquirectangular2($self, @parameters);
8025 } elsif ($params{Projection} eq 'Gauss_Schreiber_Transverse_Mercator') {
8026 SetGaussSchreiberTMercator($self, @parameters);
8027 } elsif ($params{Projection} eq 'Gall_Stereographic') {
8028 SetGS($self, @parameters);
8029 } elsif ($params{Projection} eq 'Goode_Homolosine') {
8030 SetGH($self, @parameters);
8031 } elsif ($params{Projection} eq 'Interrupted_Goode_Homolosine') {
8033 } elsif ($params{Projection} eq 'Geostationary_Satellite') {
8034 SetGEOS($self, @parameters);
8035 } elsif ($params{Projection} eq 'Gnomonic') {
8036 SetGnomonic($self, @parameters);
8037 } elsif ($params{Projection} eq 'Hotine_Oblique_Mercator') {
8038 # Hotine_Oblique_Mercator_Azimuth_Center ?
8039 SetHOM($self, @parameters);
8040 } elsif ($params{Projection} eq 'Hotine_Oblique_Mercator_Two_Point_Natural_Origin') {
8041 SetHOM2PNO($self, @parameters);
8042 } elsif ($params{Projection} eq 'Krovak') {
8043 SetKrovak($self, @parameters);
8044 } elsif ($params{Projection} eq 'Lambert_Azimuthal_Equal_Area') {
8045 SetLAEA($self, @parameters);
8046 } elsif ($params{Projection} eq 'Lambert_Conformal_Conic_2SP') {
8047 SetLCC($self, @parameters);
8048 } elsif ($params{Projection} eq 'Lambert_Conformal_Conic_1SP') {
8049 SetLCC1SP($self, @parameters);
8050 } elsif ($params{Projection} eq 'Lambert_Conformal_Conic_2SP_Belgium') {
8051 SetLCCB($self, @parameters);
8052 } elsif ($params{Projection} eq 'miller_cylindrical') {
8053 SetMC($self, @parameters);
8054 } elsif ($params{Projection} =~ /^Mercator/) {
8055 # Mercator_1SP, Mercator_2SP, Mercator_Auxiliary_Sphere ?
8056 # variant is in Variant (or Name)
8057 SetMercator($self, @parameters);
8058 } elsif ($params{Projection} eq 'Mollweide') {
8059 SetMollweide($self, @parameters);
8060 } elsif ($params{Projection} eq 'New_Zealand_Map_Grid') {
8061 SetNZMG($self, @parameters);
8062 } elsif ($params{Projection} eq 'Oblique_Stereographic') {
8063 SetOS($self, @parameters);
8064 } elsif ($params{Projection} eq 'Orthographic') {
8065 SetOrthographic($self, @parameters);
8066 } elsif ($params{Projection} eq 'Polyconic') {
8067 SetPolyconic($self, @parameters);
8068 } elsif ($params{Projection} eq 'Polar_Stereographic') {
8069 SetPS($self, @parameters);
8070 } elsif ($params{Projection} eq 'Robinson') {
8071 SetRobinson($self, @parameters);
8072 } elsif ($params{Projection} eq 'Sinusoidal') {
8073 SetSinusoidal($self, @parameters);
8074 } elsif ($params{Projection} eq 'Stereographic') {
8075 SetStereographic($self, @parameters);
8076 } elsif ($params{Projection} eq 'Swiss_Oblique_Cylindrical') {
8077 SetSOC($self, @parameters);
8078 } elsif ($params{Projection} eq 'Transverse_Mercator_South_Orientated') {
8079 SetTMSO($self, @parameters);
8080 } elsif ($params{Projection} =~ /^Transverse_Mercator/) {
8081 my($variant) = $params{Projection} =~ /^Transverse_Mercator_(\w+)/;
8082 $variant //= $params{Variant} //= $params{Name};
8084 SetTMVariant($self, $variant, @parameters) :
8085 SetTM($self, @parameters);
8086 } elsif ($params{Projection} eq 'Tunisia_Mining_Grid') {
8087 SetTMG($self, @parameters);
8088 } elsif ($params{Projection} eq 'VanDerGrinten') {
8089 SetVDG($self, @parameters);
8091 # Aitoff, Craster_Parabolic, International_Map_of_the_World_Polyconic, Laborde_Oblique_Mercator
8092 # Loximuthal, Miller_Cylindrical, Quadrilateralized_Spherical_Cube, Quartic_Authalic, Two_Point_Equidistant
8093 # Wagner_I, Wagner_II, Wagner_III, Wagner_IV, Wagner_V, Wagner_VI, Wagner_VII
8094 # Winkel_I, Winkel_II, Winkel_Tripel
8096 SetProjection($self, $params{Projection});
8099 error("Not enough information to create a spatial reference object.");
8103 #** @method SetMercator2SP()
8105 sub SetMercator2SP {
8108 #** @method StripCTParms()
8114 #** @method Validate()
8120 #** @method Geo::OSR::SpatialReference new(%params)
8122 # Create a new spatial reference object using a named parameter. This
8123 # constructor recognizes the following key words (alternative in
8124 # parenthesis): WKT (Text), Proj4, ESRI, EPSG, EPSGA, PCI, USGS, GML
8125 # (XML), URL, ERMapper (ERM), MapInfoCS (MICoordSys). The value
8126 # depends on the key.
8127 # - WKT: Well Known Text string
8128 # - Proj4: PROJ.4 string
8129 # - ESRI: reference to a list of strings (contents of ESRI .prj file)
8130 # - EPSG: EPSG code number
8131 # - EPSGA: EPSG code number (the resulting CS will have EPSG preferred axis ordering)
8132 # - PCI: listref: [PCI_projection_string, Grid_units_code, [17 cs parameters]]
8133 # - USGS: listref: [Projection_system_code, Zone, [15 cs parameters], Datum_code, Format_flag]
8135 # - URL: URL for downloading the spatial reference from
8136 # - ERMapper: listref: [Projection, Datum, Units]
8137 # - MapInfoCS: MapInfo style co-ordinate system definition
8139 # For more information, consult the import methods in <a href="http://www.gdal.org/classOGRSpatialReference.html">OGR documentation</a>.
8141 # @note ImportFrom* methods also exist but are not documented here.
8145 # $sr = Geo::OSR::SpatialReference->new( key => value );
8147 # @return a new Geo::OSR::SpatialReference object
8152 my $self = Geo::OSRc::new_SpatialReference();
8153 if (exists $param{WKT}) {
8154 ImportFromWkt($self, $param{WKT});
8155 } elsif (exists $param{Text}) {
8156 ImportFromWkt($self, $param{Text});
8157 } elsif (exists $param{Proj4}) {
8158 ImportFromProj4($self, $param{Proj4});
8159 } elsif (exists $param{ESRI}) {
8160 ImportFromESRI($self, @{$param{ESRI}});
8161 } elsif (exists $param{EPSG}) {
8162 ImportFromEPSG($self, $param{EPSG});
8163 } elsif (exists $param{EPSGA}) {
8164 ImportFromEPSGA($self, $param{EPSGA});
8165 } elsif (exists $param{PCI}) {
8166 ImportFromPCI($self, @{$param{PCI}});
8167 } elsif (exists $param{USGS}) {
8168 ImportFromUSGS($self, @{$param{USGS}});
8169 } elsif (exists $param{XML}) {
8170 ImportFromXML($self, $param{XML});
8171 } elsif (exists $param{GML}) {
8172 ImportFromGML($self, $param{GML});
8173 } elsif (exists $param{URL}) {
8174 ImportFromUrl($self, $param{URL});
8175 } elsif (exists $param{ERMapper}) {
8176 ImportFromERM($self, @{$param{ERMapper}});
8177 } elsif (exists $param{ERM}) {
8178 ImportFromERM($self, @{$param{ERM}});
8179 } elsif (exists $param{MICoordSys}) {
8180 ImportFromMICoordSys($self, $param{MICoordSys});
8181 } elsif (exists $param{MapInfoCS}) {
8182 ImportFromMICoordSys($self, $param{MapInfoCS});
8183 } elsif (exists $param{WGS}) {
8185 SetWellKnownGeogCS($self, 'WGS'.$param{WGS});
8187 confess last_error() if $@;
8189 error("Unrecognized/missing parameters: @_.");
8191 bless $self, $pkg if defined $self;