blib/lib/Geo/Gpx.pm

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