| 1 | package Geo::Gpx; | ||
| 2 | |||
| 3 | 10 | ▶ | use warnings; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 4 | 10 | ▶ | use strict; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 5 | |||
| 6 | our $VERSION = '1.07'; | ||
| 7 | |||
| 8 | 10 | ▶ | use Carp; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 9 | 10 | ▶ | use DateTime::Format::ISO8601; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 10 | 10 | ▶ | use DateTime; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 11 | 10 | ▶ | use HTML::Entities qw( encode_entities encode_entities_numeric ); |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 12 | 10 | ▶ | use Scalar::Util qw( blessed ); |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 13 | 10 | ▶ | use XML::Descent; |
|
Subroutine
BEGIN: called CC=1 SCAR=2.6
| |||
| 14 | use File::Basename; | ||
| 15 | use Cwd qw(cwd abs_path); | ||
| 16 | use Geo::Gpx::Point; | ||
| 17 | |||
| 18 | =encoding utf8 | ||
| 19 | |||
| 20 | =head1 NAME | ||
| 21 | |||
| 22 | Geo::Gpx - Create and parse GPX files | ||
| 23 | |||
| 24 | =head1 SYNOPSIS | ||
| 25 | |||
| 26 | my ($gpx, $waypoints, $tracks); | ||
| 27 | |||
| 28 | # From a filename, an open file, or an XML string: | ||
| 29 | |||
| 30 | $gpx = Geo::Gpx->new( input => $fname ); | ||
| 31 | $gpx = Geo::Gpx->new( input => $fh ); | ||
| 32 | $gpx = Geo::Gpx->new( xml => $xml ); | ||
| 33 | |||
| 34 | my $waypoints = $gpx->waypoints(); | ||
| 35 | my $tracks = $gpx->tracks(); | ||
| 36 | |||
| 37 | =head1 DESCRIPTION | ||
| 38 | |||
| 39 | C<Geo::Gpx> supports the parsing and generation of GPX data. | ||
| 40 | |||
| 41 | =cut | ||
| 42 | |||
| 43 | # Values that are encoded as attributes | ||
| 44 | my %AS_ATTR = ( | ||
| 45 | wpt => qr{^lat|lon$}, | ||
| 46 | rtept => qr{^lat|lon$}, | ||
| 47 | trkpt => qr{^lat|lon$}, | ||
| 48 | email => qr{^id|domain$}, | ||
| 49 | link => qr{^href$} | ||
| 50 | ); | ||
| 51 | |||
| 52 | my %KEY_ORDER = ( | ||
| 53 | wpt => [ | ||
| 54 | qw( | ||
| 55 | ele time magvar geoidheight name cmt desc src link sym type fix | ||
| 56 | sat hdop vdop pdop ageofdgpsdata dgpsid extensions | ||
| 57 | ) | ||
| 58 | ], | ||
| 59 | ); | ||
| 60 | |||
| 61 | # Map hash keys to GPX names | ||
| 62 | my %XMLMAP = ( | ||
| 63 | waypoints => { waypoints => 'wpt' }, | ||
| 64 | routes => { | ||
| 65 | routes => 'rte', | ||
| 66 | points => 'rtept' | ||
| 67 | }, | ||
| 68 | tracks => { | ||
| 69 | tracks => 'trk', | ||
| 70 | segments => 'trkseg', | ||
| 71 | points => 'trkpt' | ||
| 72 | } | ||
| 73 | ); | ||
| 74 | |||
| 75 | my @META; | ||
| 76 | my @ATTR; | ||
| 77 | |||
| 78 | BEGIN { | ||
| 79 | @META = qw( name desc author time keywords copyright link ); | ||
| 80 | @ATTR = qw( version ); | ||
| 81 | |||
| 82 | # Generate accessors | ||
| 83 | for my $attr ( @META, @ATTR ) { | ||
| 84 | no strict 'refs'; | ||
| 85 | *{ __PACKAGE__ . '::' . $attr } = sub { | ||
| 86 | my $self = shift; | ||
| 87 | $self->{$attr} = shift if @_; | ||
| 88 | return $self->{$attr}; | ||
| 89 | }; | ||
| 90 | } | ||
| 91 | } | ||
| 92 | |||
| 93 | sub _time_string_to_epoch { | ||
| 94 | my ( $self, $str ) = @_; | ||
| 95 | my $dt = DateTime::Format::ISO8601->parse_datetime( $str ); | ||
| 96 | return $dt->epoch | ||
| 97 | } | ||
| 98 | |||
| 99 | sub _time_epoch_to_string { | ||
| 100 | my ( $self, $tm) = @_; | ||
| 101 | $tm = DateTime->from_epoch( epoch => $tm, time_zone => 'UTC' ); | ||
| 102 | my $ts = $tm->strftime( '%Y-%m-%dT%H:%M:%S%z' ); | ||
| 103 | $ts =~ s/(\d{2})$/:$1/; | ||
| 104 | return $ts | ||
| 105 | } | ||
| 106 | |||
| 107 | sub _init_shiny_new { | ||
| 108 | my ( $self, $args ) = @_; | ||
| 109 | |||
| 110 | $self->{schema} = []; | ||
| 111 | |||
| 112 | $self->{waypoints} = []; # these need to be defined for the *_count accessors | ||
| 113 | $self->{routes} = []; | ||
| 114 | $self->{tracks} = []; | ||
| 115 | |||
| 116 | $self->{handler} = { | ||
| 117 | create => sub { | ||
| 118 | return {@_}; | ||
| 119 | }, | ||
| 120 | time => sub { | ||
| 121 | return $self->_time_epoch_to_string( $_[0] ); | ||
| 122 | }, | ||
| 123 | }; | ||
| 124 | } | ||
| 125 | |||
| 126 | =head2 Constructor | ||
| 127 | |||
| 128 | =over 4 | ||
| 129 | |||
| 130 | =item new( input => ($fname | $fh) or xml => $xml [, work_dir => $working_directory ] ) | ||
| 131 | |||
| 132 | Create and return a new C<Geo::Gpx> instance based on a *.gpx file (I<$fname>), an open filehandle (I<$fh>), or an XML string (I<$xml>). GPX 1.0 and 1.1 are supported. | ||
| 133 | |||
| 134 | The optional C<work_dir> (or C<wd> for short) specifies where to save any working files, such as with the save() method. It can be supplied as a relative path or as an absolute path. If C<work_dir> is omitted, it is set based on the path of the I<$filename> supplied or the current working directory if the constructor is called with an XML string or a filehandle (see C<< set_wd() >> for more info). | ||
| 135 | |||
| 136 | =back | ||
| 137 | |||
| 138 | =cut | ||
| 139 | |||
| 140 | sub new { | ||
| 141 | my ( $class, @args ) = @_; | ||
| 142 | my $self = bless( {}, $class ); | ||
| 143 | |||
| 144 | # CORE::time because we have our own time method. | ||
| 145 | $self->{time} = CORE::time(); | ||
| 146 | |||
| 147 | if ( @args % 2 == 0 ) { | ||
| 148 | my %args = @args; | ||
| 149 | $self->_init_shiny_new( \%args ); | ||
| 150 | |||
| 151 | if ( exists $args{input} ) { | ||
| 152 | my ($fh, $arg); | ||
| 153 | $arg = $args{input}; | ||
| 154 | $arg =~ s/~/$ENV{'HOME'}/ if $arg =~ /^~/; | ||
| 155 | if (-f $arg) { | ||
| 156 | open( $fh , '<', $arg ) or die "can't open file $arg $!"; | ||
| 157 | $self->_parse( $fh ); | ||
| 158 | $self->set_filename($arg) | ||
| 159 | } else { $self->_parse( $args{input} ) } | ||
| 160 | } | ||
| 161 | elsif ( exists $args{xml} ) { | ||
| 162 | $self->_parse( \$args{xml} ); | ||
| 163 | } | ||
| 164 | $self->set_wd( $args{work_dir} || $args{wd} ); | ||
| 165 | } | ||
| 166 | else { | ||
| 167 | croak( "Invalid arguments" ); | ||
| 168 | } | ||
| 169 | return $self | ||
| 170 | } | ||
| 171 | |||
| 172 | # Not a method | ||
| 173 | sub _trim { | ||
| 174 | my $str = shift; | ||
| 175 | $str =~ s/^\s+//; | ||
| 176 | $str =~ s/\s+$//; | ||
| 177 | $str =~ s/\s+/ /g; | ||
| 178 | return $str; | ||
| 179 | } | ||
| 180 | |||
| 181 | sub _parse { | ||
| 182 | my $self = shift; | ||
| 183 | my $source = shift; | ||
| 184 | |||
| 185 | my $p = XML::Descent->new( { Input => $source } ); | ||
| 186 | |||
| 187 | $p->on( | ||
| 188 | gpx => sub { | ||
| 189 | my ( $elem, $attr ) = @_; | ||
| 190 | |||
| 191 | $p->context( $self ); | ||
| 192 | |||
| 193 | my $version = $self->{version} = ( $attr->{version} || '1.0' ); | ||
| 194 | |||
| 195 | my $parse_deep = sub { | ||
| 196 | my ( $elem, $attr ) = @_; | ||
| 197 | my $ob = $attr; # Get attributes | ||
| 198 | $p->context( $ob ); | ||
| 199 | $p->walk(); | ||
| 200 | return $ob; | ||
| 201 | }; | ||
| 202 | |||
| 203 | # Parse a point | ||
| 204 | my $parse_point = sub { | ||
| 205 | my ( $elem, $attr ) = @_; | ||
| 206 | my $pt = $parse_deep->( $elem, $attr ); | ||
| 207 | return Geo::Gpx::Point->new( %{$pt} ) | ||
| 208 | }; | ||
| 209 | |||
| 210 | $p->on( | ||
| 211 | '*' => sub { | ||
| 212 | my ( $elem, $attr, $ctx ) = @_; | ||
| 213 | $ctx->{$elem} = _trim( $p->text() ); | ||
| 214 | }, | ||
| 215 | time => sub { | ||
| 216 | my ( $elem, $attr, $ctx ) = @_; | ||
| 217 | my $tm = $self->_time_string_to_epoch( _trim( $p->text() ) ); | ||
| 218 | $ctx->{$elem} = $tm if defined $tm; | ||
| 219 | } | ||
| 220 | ); | ||
| 221 | |||
| 222 | if ( _cmp_ver( $version, '1.1' ) >= 0 ) { | ||
| 223 | |||
| 224 | # Handle 1.1 metadata | ||
| 225 | $p->on( | ||
| 226 | metadata => sub { | ||
| 227 | $p->walk(); | ||
| 228 | }, | ||
| 229 | [ 'link', 'email', 'author' ] => sub { | ||
| 230 | my ( $elem, $attr, $ctx ) = @_; | ||
| 231 | $ctx->{$elem} = $parse_deep->( $elem, $attr ); | ||
| 232 | } | ||
| 233 | ); | ||
| 234 | } | ||
| 235 | else { | ||
| 236 | |||
| 237 | # Handle 1.0 metadata | ||
| 238 | $p->on( | ||
| 239 | url => sub { | ||
| 240 | my ( $elem, $attr, $ctx ) = @_; | ||
| 241 | $ctx->{link}->{href} = _trim( $p->text() ); | ||
| 242 | }, | ||
| 243 | urlname => sub { | ||
| 244 | my ( $elem, $attr, $ctx ) = @_; | ||
| 245 | $ctx->{link}->{text} = _trim( $p->text() ); | ||
| 246 | }, | ||
| 247 | author => sub { | ||
| 248 | my ( $elem, $attr, $ctx ) = @_; | ||
| 249 | $ctx->{author}->{name} = _trim( $p->text() ); | ||
| 250 | }, | ||
| 251 | email => sub { | ||
| 252 | my ( $elem, $attr, $ctx ) = @_; | ||
| 253 | my $em = _trim( $p->text() ); | ||
| 254 | if ( $em =~ m{^(.+)\@(.+)$} ) { | ||
| 255 | $ctx->{author}->{email} = { | ||
| 256 | id => $1, | ||
| 257 | domain => $2 | ||
| 258 | }; | ||
| 259 | } | ||
| 260 | } | ||
| 261 | ); | ||
| 262 | } | ||
| 263 | |||
| 264 | $p->on( | ||
| 265 | bounds => sub { | ||
| 266 | my ( $elem, $attr, $ctx ) = @_; | ||
| 267 | $ctx->{$elem} = $parse_deep->( $elem, $attr ); | ||
| 268 | }, | ||
| 269 | keywords => sub { | ||
| 270 | my ( $elem, $attr ) = @_; | ||
| 271 | $self->{keywords} | ||
| 272 | = [ map { _trim( $_ ) } split( /,/, $p->text() ) ]; | ||
| 273 | }, | ||
| 274 | wpt => sub { | ||
| 275 | my ( $elem, $attr ) = @_; | ||
| 276 | push @{ $self->{waypoints} }, $parse_point->( $elem, $attr ); | ||
| 277 | }, | ||
| 278 | [ 'trkpt', 'rtept' ] => sub { | ||
| 279 | my ( $elem, $attr, $ctx ) = @_; | ||
| 280 | push @{ $ctx->{points} }, $parse_point->( $elem, $attr ); | ||
| 281 | }, | ||
| 282 | rte => sub { | ||
| 283 | my ( $elem, $attr ) = @_; | ||
| 284 | my $rt = $parse_deep->( $elem, $attr ); | ||
| 285 | push @{ $self->{routes} }, $rt; | ||
| 286 | }, | ||
| 287 | trk => sub { | ||
| 288 | my ( $elem, $attr ) = @_; | ||
| 289 | my $tk = {}; | ||
| 290 | $p->context( $tk ); | ||
| 291 | $p->on( | ||
| 292 | trkseg => sub { | ||
| 293 | my ( $elem, $attr ) = @_; | ||
| 294 | my $seg = $parse_deep->( $elem, $attr ); | ||
| 295 | push @{ $tk->{segments} }, $seg; | ||
| 296 | } | ||
| 297 | ); | ||
| 298 | $p->walk(); | ||
| 299 | push @{ $self->{tracks} }, $tk; | ||
| 300 | } | ||
| 301 | ); | ||
| 302 | |||
| 303 | $p->walk(); | ||
| 304 | } | ||
| 305 | ); | ||
| 306 | |||
| 307 | $p->walk(); | ||
| 308 | } | ||
| 309 | |||
| 310 | =over 4 | ||
| 311 | |||
| 312 | =item clone() | ||
| 313 | |||
| 314 | Returns a deep copy of a C<Geo::Gpx> instance. | ||
| 315 | |||
| 316 | $clone = $self->clone; | ||
| 317 | |||
| 318 | =back | ||
| 319 | |||
| 320 | =cut | ||
| 321 | |||
| 322 | sub clone { | ||
| 323 | my $clone; | ||
| 324 | eval(Data::Dumper->Dump([ shift ], ['$clone'])); | ||
| 325 | confess $@ if $@; | ||
| 326 | return $clone | ||
| 327 | } | ||
| 328 | # actually it can clone anything | ||
| 329 | |||
| 330 | =head2 Methods | ||
| 331 | |||
| 332 | =over 4 | ||
| 333 | |||
| 334 | =item waypoints( $int or name => $name ) | ||
| 335 | |||
| 336 | Without arguments, returns the array reference of waypoints. | ||
| 337 | |||
| 338 | With an argument, returns a reference to the waypoint whose C<name> field is an exact match with I<$name> or the one at integer index I<$int> (1-indexed). Returns C<undef> if none are found such that this method can be used to check if a specific point exists (i.e. no exception is raised if I<$name> or I<$int> do not exist) . | ||
| 339 | |||
| 340 | =back | ||
| 341 | |||
| 342 | =cut | ||
| 343 | |||
| 344 | sub waypoints { | ||
| 345 | my $aref = shift->{waypoints}; | ||
| 346 | return $aref unless @_; | ||
| 347 | my $waypoint; | ||
| 348 | if (@_ == 2) { | ||
| 349 | croak "$_[0] key is not supported in waypoints()" unless $_[0] eq 'name'; | ||
| 350 | for my $pt ( @{$aref} ) { | ||
| 351 | next unless defined $pt->name; | ||
| 352 | $waypoint = $pt if $pt->name eq $_[1] | ||
| 353 | } | ||
| 354 | } else { | ||
| 355 | $waypoint = $aref->[ ($_[0] - 1) ] | ||
| 356 | } | ||
| 357 | return $waypoint | ||
| 358 | } | ||
| 359 | |||
| 360 | =over 4 | ||
| 361 | |||
| 362 | =item waypoints_add( $point or \%point [, $point or \%point, … ] ) | ||
| 363 | |||
| 364 | Add one or more waypoints. Each waypoint must be either a L<Geo::Gpx::Point> or a hash reference with fields that can be parsed by L<Geo::Gpx::Point>'s C<new()> constructor. See the later for the possible fields. | ||
| 365 | |||
| 366 | %point = ( lat => 54.786989, lon => -2.344214, ele => 512, name => 'My house' ); | ||
| 367 | $gpx->waypoints_add( \%point ); | ||
| 368 | |||
| 369 | or | ||
| 370 | |||
| 371 | $pt = Geo::Gpx::Point->new( %point ); | ||
| 372 | $gpx->waypoints_add( $pt ); | ||
| 373 | |||
| 374 | =back | ||
| 375 | |||
| 376 | =cut | ||
| 377 | |||
| 378 | sub waypoints_add { | ||
| 379 | my $self = shift; | ||
| 380 | |||
| 381 | for my $wpt ( @_ ) { | ||
| 382 | eval { keys %$wpt }; | ||
| 383 | croak "waypoint argument must be a hash reference" | ||
| 384 | if $@; | ||
| 385 | |||
| 386 | croak "'lat' and 'lon' keys are mandatory in waypoint hash" | ||
| 387 | unless exists $wpt->{lon} && exists $wpt->{lat}; | ||
| 388 | |||
| 389 | push @{ $self->{waypoints} }, Geo::Gpx::Point->new( %$wpt ); | ||
| 390 | } | ||
| 391 | #TODO: Should return 1 | ||
| 392 | } | ||
| 393 | |||
| 394 | =over 4 | ||
| 395 | |||
| 396 | =item waypoints_search( $field => $regex ) | ||
| 397 | |||
| 398 | returns an array of waypoints whose I<$field> (e.g. C<name>, C<desc>, …) matches I<$regex>. By default, the regex is case-sensitive; specify C<qr/(?i:search_string_here)/> to ignore case. | ||
| 399 | |||
| 400 | =back | ||
| 401 | |||
| 402 | =cut | ||
| 403 | |||
| 404 | sub waypoints_search { | ||
| 405 | my ($gpx, $field, $regex) = @_; | ||
| 406 | my @matches; | ||
| 407 | my $iter = $gpx->iterate_waypoints(); | ||
| 408 | while ( my $pt = $iter->() ) { | ||
| 409 | if (defined $pt->$field) { | ||
| 410 | push @matches, $pt if ($pt->$field =~ $regex) | ||
| 411 | } | ||
| 412 | } | ||
| 413 | return @matches | ||
| 414 | } | ||
| 415 | |||
| 416 | =over 4 | ||
| 417 | |||
| 418 | =item waypoints_count() | ||
| 419 | |||
| 420 | returns the number of waypoints in the object. | ||
| 421 | |||
| 422 | =back | ||
| 423 | |||
| 424 | =cut | ||
| 425 | |||
| 426 | sub waypoints_count { return scalar @{ shift->{waypoints} } } | ||
| 427 | |||
| 428 | =over 4 | ||
| 429 | |||
| 430 | =item waypoints_delete_all() | ||
| 431 | |||
| 432 | delete all waypoints. Returns true. | ||
| 433 | |||
| 434 | =back | ||
| 435 | |||
| 436 | =cut | ||
| 437 | |||
| 438 | sub waypoints_delete_all { | ||
| 439 | my $gpx = shift; | ||
| 440 | croak 'waypoints_delete_all() expects no arguments' if @_; | ||
| 441 | $gpx->{waypoints} = []; | ||
| 442 | return 1 | ||
| 443 | } | ||
| 444 | |||
| 445 | =over 4 | ||
| 446 | |||
| 447 | =item waypoint_delete( $name ) | ||
| 448 | |||
| 449 | delete the waypoint whose C<name> is an exact match, case sensitively. Returns true if successful, C<undef> if the name cannot be found. | ||
| 450 | |||
| 451 | =back | ||
| 452 | |||
| 453 | =cut | ||
| 454 | |||
| 455 | sub waypoint_delete { | ||
| 456 | my ($gpx, $name) = @_; | ||
| 457 | my ($index, $found_match) = (0, undef); | ||
| 458 | my $iter = $gpx->iterate_waypoints(); | ||
| 459 | while ( my $pt = $iter->() ) { | ||
| 460 | if (defined $pt->name) { | ||
| 461 | if ($pt->name eq $name) { | ||
| 462 | $found_match = 1; | ||
| 463 | last | ||
| 464 | } | ||
| 465 | } | ||
| 466 | ++$index | ||
| 467 | } | ||
| 468 | splice @{$gpx->{waypoints}}, $index, 1 if $found_match; | ||
| 469 | return $found_match | ||
| 470 | } | ||
| 471 | |||
| 472 | =over 4 | ||
| 473 | |||
| 474 | =item waypoints_merge( $gpx, $regex ) | ||
| 475 | |||
| 476 | Merge waypoints with those contained in the L<Geo::Gpx> instance provide as argument. Waypoints are compared based on their respective C<name> fields, which must exist in I<$gpx> (if names are missing in the current instance, all points will be merged). | ||
| 477 | |||
| 478 | A I<$regex> may be provided to limit the merge to a subset of waypoints from I<$gpx>. | ||
| 479 | |||
| 480 | Returns the number of points successfully merged (i.e. the difference in C<< $gps->waypoints_count >> before and after the merge). | ||
| 481 | |||
| 482 | =back | ||
| 483 | |||
| 484 | =cut | ||
| 485 | |||
| 486 | sub waypoints_merge { | ||
| 487 | my ($gpx1, $gpx2) = (shift, shift); | ||
| 488 | my ($regex, @to_merge); | ||
| 489 | $regex = shift if ref $_[0] eq 'Regexp'; | ||
| 490 | croak "waypoints_merge() expects a Geo::Gpx object (and optionally a regex) as arguments" if @_; | ||
| 491 | |||
| 492 | if ($regex) { @to_merge = $gpx2->waypoints_search( name => $regex ) } | ||
| 493 | else { @to_merge = @{ $gpx2->waypoints } } | ||
| 494 | croak "no waypoints to merge found" unless @to_merge; | ||
| 495 | |||
| 496 | my $before_count = $gpx1->waypoints_count; | ||
| 497 | for (0 .. $#to_merge) { | ||
| 498 | my $pt = $to_merge[$_]; | ||
| 499 | croak "points to merge must contain a name field" unless defined $pt->name; | ||
| 500 | next if $gpx1->waypoints( name => $pt->name ); # i.e. don't add if exists, could later give option force => 1 | ||
| 501 | $gpx1->waypoints_add( $pt ) | ||
| 502 | } | ||
| 503 | return $gpx1->waypoints_count - $before_count | ||
| 504 | } | ||
| 505 | |||
| 506 | =over 4 | ||
| 507 | |||
| 508 | =item waypoint_closest_to( $point of $tcx_trackpoint ) | ||
| 509 | |||
| 510 | From any L<Geo::Gpx::Point> or L<Geo::TCX::Trackpoint> object, return the waypoint that is closest to it. If called in list context, returns a two-element array consisting of that waypoint, and the distance from the coordinate (in meters). | ||
| 511 | |||
| 512 | =back | ||
| 513 | |||
| 514 | =cut | ||
| 515 | |||
| 516 | sub waypoint_closest_to { | ||
| 517 | my ($gpx, $to_pt) = (shift, shift); | ||
| 518 | my $croak_msg = 'waypoint_closest_to() expects a single argument in the form of Garmin::TCX::Trackpoint or Geo::Gpx::Point'; | ||
| 519 | if (ref $to_pt) { | ||
| 520 | croak $croak_msg unless $to_pt->isa('Geo::TCX::Trackpoint') or $to_pt->isa('Geo::Gpx::Point') | ||
| 521 | } else { croak $croak_msg } | ||
| 522 | croak $croak_msg if @_; | ||
| 523 | |||
| 524 | my $gc = $to_pt->to_geocalc; | ||
| 525 | my ($closest_pt, $min_dist); | ||
| 526 | my $iter = $gpx->iterate_waypoints(); | ||
| 527 | while ( my $pt = $iter->() ) { | ||
| 528 | my $distance = $gc->distance_to({ lat => $pt->lat, lon => $pt->lon }); | ||
| 529 | $min_dist = $distance unless (defined $min_dist); # nb: $min_dist can be 0 | ||
| 530 | $closest_pt ||= $pt; | ||
| 531 | if ($distance < $min_dist) { | ||
| 532 | # print $pt->name, " distance is smaller at: ", $distance, "\n"; | ||
| 533 | # $DB::single=1; | ||
| 534 | $closest_pt = $pt; | ||
| 535 | $min_dist = $distance | ||
| 536 | } | ||
| 537 | } | ||
| 538 | return ($closest_pt, $min_dist) if wantarray; | ||
| 539 | return $closest_pt | ||
| 540 | } | ||
| 541 | |||
| 542 | =over 4 | ||
| 543 | |||
| 544 | =item routes( integer or name => 'name' ) | ||
| 545 | |||
| 546 | Returns the array reference of routes when called without argument. Optionally accepts a single integer referring to the route number from routes aref (1-indexed) or a key value pair with the name of the route to be returned. | ||
| 547 | |||
| 548 | =back | ||
| 549 | |||
| 550 | =cut | ||
| 551 | |||
| 552 | sub routes { | ||
| 553 | my $o= shift; | ||
| 554 | return $o->{routes} unless @_; | ||
| 555 | my $route; | ||
| 556 | if (@_ == 2) { | ||
| 557 | for my $t ( @{ $o->{routes} } ) { | ||
| 558 | $route = $t if $t->{$_[0]} eq $_[1] | ||
| 559 | } | ||
| 560 | croak "no route named $_[1] in route list" unless $route | ||
| 561 | } else { | ||
| 562 | $route = $o->{routes}[($_[0] - 1)]; | ||
| 563 | croak "route $_[0] not found" unless $route | ||
| 564 | } | ||
| 565 | return $route | ||
| 566 | } | ||
| 567 | |||
| 568 | =over 4 | ||
| 569 | |||
| 570 | =item routes_add( $route or $points_aref [, name => $route_name ) | ||
| 571 | |||
| 572 | Add a route to a C<Geo::Gpx> object. The I<$route> is expected to be an existing route (i.e. a hash ref). Returns true. A new route can also be created based an array reference(s) of L<Geo::Gpx::Point> objects and added to the C<Geo::Gpx> instance. | ||
| 573 | |||
| 574 | C<name> and all other meta fields supported by routes can be provided and will overwrite any existing fields in I<$route>. | ||
| 575 | |||
| 576 | =back | ||
| 577 | |||
| 578 | =cut | ||
| 579 | |||
| 580 | sub routes_add { | ||
| 581 | my $o = shift; | ||
| 582 | my ($route, $aref); | ||
| 583 | |||
| 584 | my @args = @_; | ||
| 585 | for (@args) { | ||
| 586 | if ( ref($_) eq 'HASH' ) { | ||
| 587 | $route = shift | ||
| 588 | } elsif ( ref($_) eq 'ARRAY' ) { | ||
| 589 | $aref = shift | ||
| 590 | } | ||
| 591 | } | ||
| 592 | my %opts = @_; | ||
| 593 | |||
| 594 | my $c; | ||
| 595 | if ($aref) { | ||
| 596 | croak 'arguments to routes_add() contain both an existing route and an array reference of points, please specify only one kind of reference' if $route; | ||
| 597 | $route = { 'name' => 'Track' }; | ||
| 598 | |||
| 599 | for my $pt (@$aref) { | ||
| 600 | my $is_geo_gpx_point = blessed $pt and $pt->isa('Geo::Gpx::Point'); | ||
| 601 | $pt = Geo::Gpx::Point->new( %$pt ) unless $is_geo_gpx_point | ||
| 602 | } | ||
| 603 | $route->{points} = $aref | ||
| 604 | } | ||
| 605 | croak 'routes_add() expects an existing route or an array reference as argument' unless $route; | ||
| 606 | $c = clone( $route ); | ||
| 607 | for (keys %opts) { | ||
| 608 | $c->{$_} = $opts{$_} # need to check the $_ are legal | ||
| 609 | } | ||
| 610 | push @{ $o->{routes} }, $c; | ||
| 611 | return 1 | ||
| 612 | } | ||
| 613 | |||
| 614 | =over 4 | ||
| 615 | |||
| 616 | =item routes_count() | ||
| 617 | |||
| 618 | returns the number of routes in the object. | ||
| 619 | |||
| 620 | =back | ||
| 621 | |||
| 622 | =cut | ||
| 623 | |||
| 624 | sub routes_count { return scalar @{ shift->{routes} } } | ||
| 625 | |||
| 626 | =over 4 | ||
| 627 | |||
| 628 | =item tracks( integer or name => 'name' ) | ||
| 629 | |||
| 630 | Returns the array reference of tracks when called without argument. Optionally accepts a single integer referring to the track number from tracks aref (1-indexed) or a key value pair with the name of the track to be returned. | ||
| 631 | |||
| 632 | =back | ||
| 633 | |||
| 634 | =cut | ||
| 635 | |||
| 636 | sub tracks { | ||
| 637 | my $o= shift; | ||
| 638 | return $o->{tracks} unless @_; | ||
| 639 | my $track; | ||
| 640 | if (@_ == 2) { | ||
| 641 | for my $t ( @{ $o->{tracks} } ) { | ||
| 642 | $track = $t if $t->{$_[0]} eq $_[1] | ||
| 643 | } | ||
| 644 | croak "no track named $_[1] in track list" unless $track | ||
| 645 | } else { | ||
| 646 | $track = $o->{tracks}[($_[0] - 1)]; | ||
| 647 | croak "track $_[0] not found" unless $track | ||
| 648 | } | ||
| 649 | return $track | ||
| 650 | } | ||
| 651 | |||
| 652 | =over 4 | ||
| 653 | |||
| 654 | =item tracks_add( $track or $points_aref [, $points_aref, … ] [, name => $track_name ] ) | ||
| 655 | |||
| 656 | Add a track to a C<Geo::Gpx> object. The I<$track> is expected to be an existing track (i.e. a hash ref). Returns true. | ||
| 657 | |||
| 658 | If I<$track> has no C<name> field and none is provided, the timestamp of the first point of the track will be used (this is experimental and may change in the future). All other fields supported by tracks can be provided and will overwrite any existing fields in I<$track>. | ||
| 659 | |||
| 660 | A new track can also be created based an array reference(s) of L<Geo::Gpx::Point> objects and added to the C<Geo::Gpx> instance. If more than one array reference is supplied, the resulting track will contain as many segments as the number of aref's provided. | ||
| 661 | |||
| 662 | =back | ||
| 663 | |||
| 664 | =cut | ||
| 665 | |||
| 666 | sub tracks_add { | ||
| 667 | my $o = shift; | ||
| 668 | my ($track, @arefs); | ||
| 669 | |||
| 670 | my @args = @_; | ||
| 671 | for (@args) { | ||
| 672 | if ( ref($_) eq 'HASH' ) { | ||
| 673 | $track = shift | ||
| 674 | } elsif ( ref($_) eq 'ARRAY' ) { | ||
| 675 | push @arefs, shift | ||
| 676 | } | ||
| 677 | } | ||
| 678 | my %opts = @_; | ||
| 679 | |||
| 680 | # Q: do we need to check that $o->{tracks} does not already contain a track of the same name? | ||
| 681 | # - if so we would do here (unless not yet possible) but it's relevant to method way of adding a track | ||
| 682 | # Q: is the name key mandatory? check the schema | ||
| 683 | |||
| 684 | my $c; | ||
| 685 | if (@arefs) { | ||
| 686 | croak 'arguments to tracks_add() contain both an existing track and an array reference of points, please specify only one kind of reference' if $track; | ||
| 687 | # $track = { 'name' => 'Track', 'segments' => [] }; | ||
| 688 | $track = { 'segments' => [] }; # commented line was just to show the structure of the aref, the name is not required | ||
| 689 | |||
| 690 | for my $i (0 .. $#arefs) { | ||
| 691 | my $points = $arefs[$i]; | ||
| 692 | for my $pt (@{$points}) { | ||
| 693 | my $is_geo_gpx_point = blessed $pt and $pt->isa('Geo::Gpx::Point'); | ||
| 694 | $pt = Geo::Gpx::Point->new( %$pt ) unless $is_geo_gpx_point | ||
| 695 | } | ||
| 696 | $track->{segments}[$i]{points} = $points | ||
| 697 | } | ||
| 698 | } else { | ||
| 699 | croak 'tracks_add() expects an existing track or an array reference as argument' unless $track | ||
| 700 | } | ||
| 701 | $c = clone( $track ); | ||
| 702 | for (keys %opts) { | ||
| 703 | $c->{$_} = $opts{$_} # need to check the $_ are legal | ||
| 704 | } | ||
| 705 | |||
| 706 | # let's try a default behaviour of adding time of first point if name is not defined (could provide option to turn this off) | ||
| 707 | if ( ! defined $c->{name} ) { | ||
| 708 | my $first_pt_time = $c->{segments}[0]{points}[0]->time; | ||
| 709 | $c->{name} = $o->_time_epoch_to_string( $first_pt_time ) if $first_pt_time; | ||
| 710 | } | ||
| 711 | push @{ $o->{tracks} }, $c; | ||
| 712 | return 1 | ||
| 713 | } | ||
| 714 | |||
| 715 | =over 4 | ||
| 716 | |||
| 717 | =item tracks_count() | ||
| 718 | |||
| 719 | returns the number of tracks in the object. | ||
| 720 | |||
| 721 | =back | ||
| 722 | |||
| 723 | =cut | ||
| 724 | |||
| 725 | sub tracks_count { return scalar @{ shift->{tracks} } } | ||
| 726 | |||
| 727 | # Not a method | ||
| 728 | sub _iterate_points { | ||
| 729 | my $pts = shift || []; # array ref | ||
| 730 | |||
| 731 | unless ( defined $pts ) { | ||
| 732 | return sub { | ||
| 733 | return; | ||
| 734 | }; | ||
| 735 | } | ||
| 736 | |||
| 737 | my $max = scalar( @{$pts} ); | ||
| 738 | my $pos = 0; | ||
| 739 | return sub { | ||
| 740 | return if $pos >= $max; | ||
| 741 | return $pts->[ $pos++ ]; | ||
| 742 | }; | ||
| 743 | } | ||
| 744 | |||
| 745 | # Not a method | ||
| 746 | sub _iterate_iterators { | ||
| 747 | my @its = @_; | ||
| 748 | return sub { | ||
| 749 | for ( ;; ) { | ||
| 750 | return undef unless @its; | ||
| 751 | my $next = $its[0]->(); | ||
| 752 | return $next if defined $next; | ||
| 753 | shift @its; | ||
| 754 | } | ||
| 755 | } | ||
| 756 | } | ||
| 757 | |||
| 758 | =over 4 | ||
| 759 | |||
| 760 | =item iterate_waypoints() | ||
| 761 | |||
| 762 | =item iterate_trackpoints() | ||
| 763 | |||
| 764 | =item iterate_routepoints() | ||
| 765 | |||
| 766 | Get an iterator for all of the waypoints, trackpoints, or routepoints in a C<Geo::Gpx> instance, as per the iterator chosen. | ||
| 767 | |||
| 768 | =cut | ||
| 769 | |||
| 770 | sub iterate_waypoints { | ||
| 771 | my $self = shift; | ||
| 772 | return _iterate_points( $self->{waypoints} ); | ||
| 773 | } | ||
| 774 | |||
| 775 | sub iterate_routepoints { | ||
| 776 | my $self = shift; | ||
| 777 | |||
| 778 | my @iter = (); | ||
| 779 | if ( exists( $self->{routes} ) ) { | ||
| 780 | for my $rte ( @{ $self->{routes} } ) { | ||
| 781 | push @iter, _iterate_points( $rte->{points} ); | ||
| 782 | } | ||
| 783 | } | ||
| 784 | |||
| 785 | return _iterate_iterators( @iter ); | ||
| 786 | |||
| 787 | } | ||
| 788 | |||
| 789 | sub iterate_trackpoints { | ||
| 790 | my $self = shift; | ||
| 791 | |||
| 792 | my @iter = (); | ||
| 793 | if ( exists( $self->{tracks} ) ) { | ||
| 794 | for my $trk ( @{ $self->{tracks} } ) { | ||
| 795 | if ( exists( $trk->{segments} ) ) { | ||
| 796 | for my $seg ( @{ $trk->{segments} } ) { | ||
| 797 | push @iter, _iterate_points( $seg->{points} ); | ||
| 798 | } | ||
| 799 | } | ||
| 800 | } | ||
| 801 | } | ||
| 802 | |||
| 803 | return _iterate_iterators( @iter ); | ||
| 804 | } | ||
| 805 | |||
| 806 | =item iterate_points() | ||
| 807 | |||
| 808 | Get an iterator for all of the points in a C<Geo::Gpx> instance, including waypoints, trackpoints, and routepoints. | ||
| 809 | |||
| 810 | my $iter = $gpx->iterate_points(); | ||
| 811 | while ( my $pt = $iter->() ) { | ||
| 812 | print "Point: ", join( ', ', $pt->{lat}, $pt->{lon} ), "\n"; | ||
| 813 | } | ||
| 814 | |||
| 815 | =back | ||
| 816 | |||
| 817 | =cut | ||
| 818 | |||
| 819 | sub iterate_points { | ||
| 820 | my $self = shift; | ||
| 821 | |||
| 822 | return _iterate_iterators( | ||
| 823 | $self->iterate_waypoints(), | ||
| 824 | $self->iterate_routepoints(), | ||
| 825 | $self->iterate_trackpoints() | ||
| 826 | ); | ||
| 827 | } | ||
| 828 | |||
| 829 | =over 4 | ||
| 830 | |||
| 831 | =item bounds( $iterator ) | ||
| 832 | |||
| 833 | Compute the bounding box of all the points in a C<Geo::Gpx> returning the result as a hash reference. | ||
| 834 | |||
| 835 | my $gpx = Geo::Gpx->new( xml => $some_xml ); | ||
| 836 | my $bounds = $gpx->bounds(); | ||
| 837 | |||
| 838 | returns a structure like this: | ||
| 839 | |||
| 840 | $bounds = { | ||
| 841 | minlat => 57.120939, | ||
| 842 | minlon => -2.9839832, | ||
| 843 | maxlat => 57.781729, | ||
| 844 | maxlon => -1.230902 | ||
| 845 | }; | ||
| 846 | |||
| 847 | C<$iterator> defaults to C<$self-E<gt>iterate_points> if not specified. | ||
| 848 | |||
| 849 | =cut | ||
| 850 | |||
| 851 | sub bounds { | ||
| 852 | my ( $self, $iter ) = @_; | ||
| 853 | $iter ||= $self->iterate_points; | ||
| 854 | |||
| 855 | my $bounds = {}; | ||
| 856 | |||
| 857 | while ( my $pt = $iter->() ) { | ||
| 858 | $bounds->{minlat} = $pt->{lat} | ||
| 859 | if !defined $bounds->{minlat} || $pt->{lat} < $bounds->{minlat}; | ||
| 860 | $bounds->{maxlat} = $pt->{lat} | ||
| 861 | if !defined $bounds->{maxlat} || $pt->{lat} > $bounds->{maxlat}; | ||
| 862 | $bounds->{minlon} = $pt->{lon} | ||
| 863 | if !defined $bounds->{minlon} || $pt->{lon} < $bounds->{minlon}; | ||
| 864 | $bounds->{maxlon} = $pt->{lon} | ||
| 865 | if !defined $bounds->{maxlon} || $pt->{lon} > $bounds->{maxlon}; | ||
| 866 | } | ||
| 867 | |||
| 868 | return $bounds; | ||
| 869 | } | ||
| 870 | |||
| 871 | sub _enc { | ||
| 872 | return encode_entities_numeric( $_[0] ); | ||
| 873 | } | ||
| 874 | |||
| 875 | sub _tag { | ||
| 876 | my $name = shift; | ||
| 877 | my $attr = shift || {}; | ||
| 878 | my @tag = ( '<', $name ); | ||
| 879 | |||
| 880 | # Sort keys so the tests can depend on hash output order | ||
| 881 | for my $n ( sort keys %{$attr} ) { | ||
| 882 | my $v = $attr->{$n}; | ||
| 883 | push @tag, ' ', $n, '="', _enc( $v ), '"'; | ||
| 884 | } | ||
| 885 | |||
| 886 | if ( @_ ) { | ||
| 887 | push @tag, '>', @_, '</', $name, ">\n"; | ||
| 888 | } | ||
| 889 | else { | ||
| 890 | push @tag, " />\n"; | ||
| 891 | } | ||
| 892 | |||
| 893 | return join( '', @tag ); | ||
| 894 | } | ||
| 895 | |||
| 896 | sub _xml { | ||
| 897 | my $self = shift; | ||
| 898 | my $name = shift; | ||
| 899 | my $value = shift; | ||
| 900 | my $name_map = shift || {}; | ||
| 901 | |||
| 902 | my $tag = $name_map->{$name} || $name; | ||
| 903 | my $is_geo_gpx_point = blessed $value and $value->isa('Geo::Gpx::Point'); | ||
| 904 | |||
| 905 | if ( defined( my $enc = $self->{encoder}->{$name} ) ) { | ||
| 906 | return $enc->( $name, $value ); | ||
| 907 | } | ||
| 908 | elsif ( ref $value eq 'HASH' or $is_geo_gpx_point ) { | ||
| 909 | my $attr = {}; | ||
| 910 | my @cont = ( "\n" ); | ||
| 911 | my $as_attr = $AS_ATTR{$name}; | ||
| 912 | |||
| 913 | # Shallow copy so we can delete keys as we output them | ||
| 914 | my %v = %{$value}; | ||
| 915 | for my $k ( @{ $KEY_ORDER{$name} || [] }, sort keys %v ) { | ||
| 916 | if ( defined( my $vv = delete $v{$k} ) ) { | ||
| 917 | if ( defined $as_attr && $k =~ $as_attr ) { | ||
| 918 | $attr->{$k} = $vv; | ||
| 919 | } | ||
| 920 | else { | ||
| 921 | push @cont, $self->_xml( $k, $vv, $name_map ); | ||
| 922 | } | ||
| 923 | } | ||
| 924 | } | ||
| 925 | |||
| 926 | return _tag( $tag, $attr, @cont ); | ||
| 927 | } | ||
| 928 | elsif ( ref $value eq 'ARRAY' ) { | ||
| 929 | return join '', | ||
| 930 | map { $self->_xml( $tag, $_, $name_map ) } @{$value}; | ||
| 931 | } | ||
| 932 | else { | ||
| 933 | return _tag( $tag, {}, _enc( $value ) ); | ||
| 934 | } | ||
| 935 | } | ||
| 936 | |||
| 937 | sub _cmp_ver { | ||
| 938 | my ( $v1, $v2 ) = @_; | ||
| 939 | my @v1 = split( /[.]/, $v1 ); | ||
| 940 | my @v2 = split( /[.]/, $v2 ); | ||
| 941 | |||
| 942 | while ( @v1 && @v2 ) { | ||
| 943 | my $cmp = ( shift @v1 <=> shift @v2 ); | ||
| 944 | return $cmp if $cmp; | ||
| 945 | } | ||
| 946 | |||
| 947 | return @v1 <=> @v2; | ||
| 948 | } | ||
| 949 | |||
| 950 | =item xml( $version ) | ||
| 951 | |||
| 952 | Generate and return an XML string representation of the instance. | ||
| 953 | |||
| 954 | If the version is omitted it defaults to the value of the C<version> attribute. Parsing a GPX document sets the version. If the C<version> attribute is unset defaults to 1.0. | ||
| 955 | |||
| 956 | =cut | ||
| 957 | |||
| 958 | sub xml { | ||
| 959 | my $self = shift; | ||
| 960 | my $version = shift || $self->{version} || '1.0'; | ||
| 961 | |||
| 962 | my @ret = (); | ||
| 963 | |||
| 964 | push @ret, qq{<?xml version="1.0" encoding="utf-8"?>\n}; | ||
| 965 | |||
| 966 | $self->{encoder} = { | ||
| 967 | time => sub { | ||
| 968 | my ( $n, $v ) = @_; | ||
| 969 | return _tag( $n, {}, _enc( $self->{handler}->{time}->( $v ) ) ); | ||
| 970 | }, | ||
| 971 | keywords => sub { | ||
| 972 | my ( $n, $v ) = @_; | ||
| 973 | return _tag( $n, {}, _enc( join( ', ', @{$v} ) ) ); | ||
| 974 | } | ||
| 975 | }; | ||
| 976 | |||
| 977 | # Limit to the latest version we know about | ||
| 978 | if ( _cmp_ver( $version, '1.1' ) >= 0 ) { | ||
| 979 | $version = '1.1'; | ||
| 980 | } | ||
| 981 | else { | ||
| 982 | |||
| 983 | # Modify encoder | ||
| 984 | $self->{encoder}->{link} = sub { | ||
| 985 | my ( $n, $v ) = @_; | ||
| 986 | my @v = (); | ||
| 987 | push @v, $self->_xml( 'url', $v->{href} ) | ||
| 988 | if exists( $v->{href} ); | ||
| 989 | push @v, $self->_xml( 'urlname', $v->{text} ) | ||
| 990 | if exists( $v->{text} ); | ||
| 991 | return join( '', @v ); | ||
| 992 | }; | ||
| 993 | $self->{encoder}->{email} = sub { | ||
| 994 | my ( $n, $v ) = @_; | ||
| 995 | if ( exists( $v->{id} ) && exists( $v->{domain} ) ) { | ||
| 996 | return _tag( 'email', {}, | ||
| 997 | _enc( join( '@', $v->{id}, $v->{domain} ) ) ); | ||
| 998 | } | ||
| 999 | else { | ||
| 1000 | return ''; | ||
| 1001 | } | ||
| 1002 | }; | ||
| 1003 | $self->{encoder}->{author} = sub { | ||
| 1004 | my ( $n, $v ) = @_; | ||
| 1005 | my @v = (); | ||
| 1006 | push @v, _tag( 'author', {}, _enc( $v->{name} ) ) | ||
| 1007 | if exists( $v->{name} ); | ||
| 1008 | push @v, $self->_xml( 'email', $v->{email} ) | ||
| 1009 | if exists( $v->{email} ); | ||
| 1010 | return join( '', @v ); | ||
| 1011 | }; | ||
| 1012 | } | ||
| 1013 | |||
| 1014 | # Turn version into path element | ||
| 1015 | ( my $vpath = $version ) =~ s{[.]}{/}g; | ||
| 1016 | |||
| 1017 | my $ns = "http://www.topografix.com/GPX/$vpath"; | ||
| 1018 | my $schema = join( ' ', $ns, "$ns/gpx.xsd", @{ $self->{schema} } ); | ||
| 1019 | |||
| 1020 | push @ret, qq{<gpx xmlns:xsd="http://www.w3.org/2001/XMLSchema" }, | ||
| 1021 | qq{xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" }, | ||
| 1022 | qq{version="$version" creator="Geo::Gpx" }, | ||
| 1023 | qq{xsi:schemaLocation="$schema" }, qq{xmlns="$ns">\n}; | ||
| 1024 | |||
| 1025 | my @meta = (); | ||
| 1026 | |||
| 1027 | for my $fld ( @META ) { | ||
| 1028 | if ( exists( $self->{$fld} ) ) { | ||
| 1029 | push @meta, $self->_xml( $fld, $self->{$fld} ); | ||
| 1030 | } | ||
| 1031 | } | ||
| 1032 | |||
| 1033 | my $bounds = $self->bounds( $self->iterate_points() ); | ||
| 1034 | if ( %{$bounds} ) { | ||
| 1035 | push @meta, _tag( 'bounds', $bounds ); | ||
| 1036 | } | ||
| 1037 | |||
| 1038 | # Version 1.1 nests metadata in a metadata tag | ||
| 1039 | if ( _cmp_ver( $version, '1.1' ) >= 0 ) { | ||
| 1040 | push @ret, _tag( 'metadata', {}, "\n", @meta ); | ||
| 1041 | } | ||
| 1042 | else { | ||
| 1043 | push @ret, @meta; | ||
| 1044 | } | ||
| 1045 | |||
| 1046 | my @existing_keys; # waypoints should be generated first, applications like MapSource croak if not | ||
| 1047 | for my $k ( sort keys %XMLMAP ) { | ||
| 1048 | if ( exists( $self->{$k} ) ) { | ||
| 1049 | if ($k eq 'waypoints') { unshift @existing_keys, $k } | ||
| 1050 | else { push @existing_keys, $k } | ||
| 1051 | } | ||
| 1052 | } | ||
| 1053 | |||
| 1054 | for my $k ( @existing_keys ) { | ||
| 1055 | push @ret, $self->_xml( $k, $self->{$k}, $XMLMAP{$k} ); | ||
| 1056 | } | ||
| 1057 | |||
| 1058 | push @ret, qq{</gpx>\n}; | ||
| 1059 | |||
| 1060 | return join( '', @ret ); | ||
| 1061 | } | ||
| 1062 | |||
| 1063 | =item TO_JSON | ||
| 1064 | |||
| 1065 | For compatibility with L<JSON> modules. Convert this object to a hash with keys that correspond to the above methods. Generated ala: | ||
| 1066 | |||
| 1067 | my %json = map { $_ => $self->$_ } | ||
| 1068 | qw(name desc author keywords copyright | ||
| 1069 | time link waypoints tracks routes version ); | ||
| 1070 | $json{bounds} = $self->bounds( $iter ); | ||
| 1071 | |||
| 1072 | With one difference: the keys will only be set if they are defined. | ||
| 1073 | |||
| 1074 | =back | ||
| 1075 | |||
| 1076 | =cut | ||
| 1077 | |||
| 1078 | sub TO_JSON { | ||
| 1079 | my $self = shift; | ||
| 1080 | my %json; #= map {$_ => $self->$_} ... | ||
| 1081 | my @keys = (@META, @ATTR); | ||
| 1082 | push @keys, 'waypoints' if $self->waypoints_count; | ||
| 1083 | push @keys, 'routes' if $self->routes_count; | ||
| 1084 | push @keys, 'tracks' if $self->tracks_count; | ||
| 1085 | |||
| 1086 | for my $key ( @keys ) { | ||
| 1087 | my $val = $self->$key; | ||
| 1088 | $json{$key} = $val if defined $val; | ||
| 1089 | } | ||
| 1090 | if ( my $bounds = $self->bounds ) { | ||
| 1091 | $json{bounds} = $self->bounds; | ||
| 1092 | } | ||
| 1093 | return \%json; | ||
| 1094 | } | ||
| 1095 | |||
| 1096 | =over 4 | ||
| 1097 | |||
| 1098 | =item save( filename => $fname, key/values ) | ||
| 1099 | |||
| 1100 | Saves the C<Geo::Gpx> instance as a file. | ||
| 1101 | |||
| 1102 | The filename field is optional unless the instance was created without a filename (i.e with an XML string or a filehandle) and C<set_filename()> has not been called yet. If the filename is a relative path, the file will be saved in the instance's working directory (not the caller's, C<Cwd>). | ||
| 1103 | |||
| 1104 | I<key/values> are (all optional): | ||
| 1105 | |||
| 1106 | Z<> C<force>: overwrites existing files if true, otherwise it won't. | ||
| 1107 | Z<> C<extensions>: save C<< <extensions>…</extension> >> tags if true (defaults to false). | ||
| 1108 | Z<> C<meta_time>: save the C<< <time>…</time> >> tag in the file's meta information tags if true (defaults to false). Some applications like MapSource return an error if this tags is present. (All other time tags elsewhere are kept.) | ||
| 1109 | |||
| 1110 | =back | ||
| 1111 | |||
| 1112 | =cut | ||
| 1113 | |||
| 1114 | sub save { | ||
| 1115 | my ($o, %opts) = @_; | ||
| 1116 | my ($fh, $fname, $xml_string); | ||
| 1117 | if ( $opts{filename} ) { $fname = $o->set_filename( $opts{filename} ) } | ||
| 1118 | else { $fname = $o->set_filename() } | ||
| 1119 | croak "$fname already exists" if -f $fname and !$opts{force}; | ||
| 1120 | |||
| 1121 | $xml_string = $o->xml; | ||
| 1122 | if ( ! $opts{extensions} ) { | ||
| 1123 | $xml_string =~ s/\n*\w*<extensions>[^<]*<\/extensions>//gs | ||
| 1124 | } | ||
| 1125 | if ( ! $opts{meta_time} ) { | ||
| 1126 | $xml_string =~ s/\n*\w*<time>[^<]*<\/time>//; | ||
| 1127 | } | ||
| 1128 | if ( ! $opts{time_nano} ) { # undocumented for now | ||
| 1129 | $xml_string =~ s/(<time>.*?)\+\d{2,2}:\d{2,2}(<\/time>)/$1Z$2/g; | ||
| 1130 | $xml_string =~ s/(<name>.*?)\+\d{2,2}:\d{2,2}(<\/name>)/$1Z$2/g | ||
| 1131 | } | ||
| 1132 | |||
| 1133 | if (defined ($opts{encoding}) and ( $opts{encoding} eq 'latin1') ) { | ||
| 1134 | open( $fh, ">:encoding(latin1)", $fname) or die "can't open file $fname: $!"; | ||
| 1135 | } else { | ||
| 1136 | open( $fh, ">:encoding(utf-8)", $fname) or die "can't open file $fname: $!"; | ||
| 1137 | } | ||
| 1138 | print $fh $xml_string | ||
| 1139 | } | ||
| 1140 | |||
| 1141 | =over 4 | ||
| 1142 | |||
| 1143 | =item set_filename( $filename ) | ||
| 1144 | |||
| 1145 | Sets/gets the filename. Returns the name of the file with the complete path. | ||
| 1146 | |||
| 1147 | =back | ||
| 1148 | |||
| 1149 | =cut | ||
| 1150 | |||
| 1151 | sub set_filename { | ||
| 1152 | my ($o, $fname) = (shift, shift); | ||
| 1153 | return $o->{_fileABSOLUTENAME} unless $fname; | ||
| 1154 | croak 'set_filename() takes only a single name as argument' if @_; | ||
| 1155 | my $wd; | ||
| 1156 | if ($o->_is_wd_defined) { $wd = $o->set_wd } | ||
| 1157 | # set_filename gets called before set_wd by new() so can't access work_dir until initialized | ||
| 1158 | |||
| 1159 | my ($name, $path, $ext); | ||
| 1160 | ($name, $path, $ext) = fileparse( $fname, '\..*' ); | ||
| 1161 | if ($wd) { | ||
| 1162 | if ( ! ($fname =~ /^\// ) ) { | ||
| 1163 | # ie if fname is not an abolsute path, adjust $path to be relative to work_dir | ||
| 1164 | ($name, $path, $ext) = fileparse( $wd . $fname, '\..*' ) | ||
| 1165 | } | ||
| 1166 | } | ||
| 1167 | $o->{_fileABSOLUTEPATH} = abs_path( $path ) . '/'; | ||
| 1168 | $o->{_fileABSOLUTENAME} = $o->{_fileABSOLUTEPATH} . $name . $ext; | ||
| 1169 | croak 'directory ' . $o->{_fileABSOLUTEPATH} . ' doesn\'t exist' unless -d $o->{_fileABSOLUTEPATH}; | ||
| 1170 | $o->{_fileNAME} = $name; | ||
| 1171 | $o->{_filePATH} = $path; | ||
| 1172 | $o->{_fileEXT} = $ext; | ||
| 1173 | $o->{_filePARSEDNAME} = $fname; | ||
| 1174 | # _file* keys only for debugging, should not be used anywhere else | ||
| 1175 | return $o->{_fileABSOLUTENAME} | ||
| 1176 | } | ||
| 1177 | |||
| 1178 | =over 4 | ||
| 1179 | |||
| 1180 | =item set_wd( $folder ) | ||
| 1181 | |||
| 1182 | Sets/gets the working directory for any eventual saving of the *.gpx file and checks the validity of that path. It can can be set as a relative path (i.e. relative to the actual L<Cwd::cwd>) or as an absolute path, but is always returned as a full path. | ||
| 1183 | |||
| 1184 | This working directory is always defined. The previous one is also stored in memory, such that C<set_wd('-')> switches back and forth between two directories. The module never actually L<chdir>'s, it just keeps track of where the user wishes to save files. | ||
| 1185 | |||
| 1186 | =back | ||
| 1187 | |||
| 1188 | =cut | ||
| 1189 | |||
| 1190 | sub set_wd { | ||
| 1191 | my ($o, $dir) = (shift, shift); | ||
| 1192 | croak 'set_wd() takes only a single folder as argument' if @_; | ||
| 1193 | my $first_call = ! $o->_is_wd_defined; # ie if called for 1st time -- at construction by new() | ||
| 1194 | |||
| 1195 | if (! $dir) { | ||
| 1196 | return $o->{work_dir} unless $first_call; | ||
| 1197 | my $fname = $o->set_filename; | ||
| 1198 | if ($fname) { | ||
| 1199 | my ($name, $path, $ext) = fileparse( $fname ); | ||
| 1200 | $o->set_wd( $path ) | ||
| 1201 | } else { $o->set_wd( cwd ) } | ||
| 1202 | } else { | ||
| 1203 | $dir =~ s/^\s+|\s+$//g; # some clean-up | ||
| 1204 | $dir =~ s/~/$ENV{'HOME'}/ if $dir =~ /^~/; | ||
| 1205 | $dir = $o->_set_wd_old if $dir eq '-'; | ||
| 1206 | |||
| 1207 | if ($dir =~ m,^[^/], ) { # convert rel path to full | ||
| 1208 | $dir = $first_call ? cwd . '/' . $dir : $o->{work_dir} . $dir | ||
| 1209 | } | ||
| 1210 | $dir =~ s,/*$,/,; # some more cleaning | ||
| 1211 | 1 while ( $dir =~ s,/\./,/, ); # support '.' | ||
| 1212 | 1 while ( $dir =~ s,[^/]+/\.\./,, ); # and '..' | ||
| 1213 | croak "$dir not a valid directory" unless -d $dir; | ||
| 1214 | |||
| 1215 | if ($first_call) { $o->_set_wd_old( $dir ) } | ||
| 1216 | else { $o->_set_wd_old( $o->{work_dir} ) } | ||
| 1217 | $o->{work_dir} = $dir | ||
| 1218 | } | ||
| 1219 | return $o->{work_dir} | ||
| 1220 | } | ||
| 1221 | |||
| 1222 | # if ($o->set_filename) { $o->set_wd() } # if we have a filename | ||
| 1223 | # else { $o->set_wd( cwd ) } # if we don't | ||
| 1224 | |||
| 1225 | sub _set_wd_old { | ||
| 1226 | my ($o, $dir) = @_; | ||
| 1227 | $o->{work_dir_old} = $dir if $dir; | ||
| 1228 | return $o->{work_dir_old} | ||
| 1229 | } | ||
| 1230 | |||
| 1231 | sub _is_wd_defined { return defined shift->{work_dir} } | ||
| 1232 | |||
| 1233 | =head2 Accessors | ||
| 1234 | |||
| 1235 | =over 4 | ||
| 1236 | |||
| 1237 | =item name( $str ) | ||
| 1238 | |||
| 1239 | =item desc( $str ) | ||
| 1240 | |||
| 1241 | =item copyright( $str ) | ||
| 1242 | |||
| 1243 | =item keywords( $aref ) | ||
| 1244 | |||
| 1245 | Accessors to get or set the C<name>, C<desc>, C<copyright>, or C<keywords> fields of the C<Geo::Gpx> instance. | ||
| 1246 | |||
| 1247 | =item author( $href ) | ||
| 1248 | |||
| 1249 | The author information is stored in a hash that reflects the structure of a GPX 1.1 document. To set it, supply a hash reference as (C<link> and C<email> are optional): | ||
| 1250 | { | ||
| 1251 | link => { text => 'Hexten', href => 'http://hexten.net/' }, | ||
| 1252 | email => { domain => 'hexten.net', id => 'andy' }, | ||
| 1253 | name => 'Andy Armstrong' | ||
| 1254 | }, | ||
| 1255 | |||
| 1256 | =item link( $href ) | ||
| 1257 | |||
| 1258 | The link is stored similarly to the author information, it can be set by supplying a hash reference as: | ||
| 1259 | { link => { text => 'Hexten', href => 'http://hexten.net/' } } | ||
| 1260 | |||
| 1261 | =item time( $epoch ) | ||
| 1262 | |||
| 1263 | Accessor for the <time> element of a GPX. The time is converted to a Unix epoch time when a GPX document is parsed, therefore only epoch time is supported for setting. | ||
| 1264 | |||
| 1265 | =item version() | ||
| 1266 | |||
| 1267 | Returns the schema version of a GPX document. Versions 1.0 and 1.1 are supported. | ||
| 1268 | |||
| 1269 | =back | ||
| 1270 | |||
| 1271 | =head1 DEPENDENCIES | ||
| 1272 | |||
| 1273 | L<DateTime::Format::ISO8601>, | ||
| 1274 | L<DateTime>, | ||
| 1275 | L<HTML::Entities>, | ||
| 1276 | L<Scalar::Util>, | ||
| 1277 | L<XML::Descent> | ||
| 1278 | |||
| 1279 | =head1 SEE ALSO | ||
| 1280 | |||
| 1281 | L<JSON> | ||
| 1282 | |||
| 1283 | =head1 BUGS AND LIMITATIONS | ||
| 1284 | |||
| 1285 | No bugs have been reported. | ||
| 1286 | |||
| 1287 | Please report any bugs or feature requests to C<bug-geo-gpx@rt.cpan.org>, or through the web interface at L<http://rt.cpan.org>. | ||
| 1288 | |||
| 1289 | =head1 AUTHOR | ||
| 1290 | |||
| 1291 | Originally by Rich Bowen C<< <rbowen@rcbowen.com> >> and Andy Armstrong C<< <andy@hexten.net> >>. | ||
| 1292 | |||
| 1293 | This version by Patrick Joly C<< <patjol@cpan.org> >>. | ||
| 1294 | |||
| 1295 | Please visit the project page at: L<https://github.com/patjoly/geo-gpx>. | ||
| 1296 | |||
| 1297 | =head1 VERSION | ||
| 1298 | |||
| 1299 | 1.07 | ||
| 1300 | |||
| 1301 | =head1 LICENSE AND COPYRIGHT | ||
| 1302 | |||
| 1303 | Copyright (c) 2004-2022, Andy Armstrong C<< <andy@hexten.net> >>, Patrick Joly C<< patjol@cpan.org >>. All rights reserved. | ||
| 1304 | |||
| 1305 | This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See L<perlartistic>. | ||
| 1306 | |||
| 1307 | =head1 DISCLAIMER OF WARRANTY | ||
| 1308 | |||
| 1309 | BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR, OR CORRECTION. | ||
| 1310 | |||
| 1311 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENSE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. | ||
| 1312 | |||
| 1313 | =cut | ||
| 1314 | |||
| 1315 | 1; | ||
| 1316 | |||