blib/lib/Geo/Gpx/Point.pm

filter: Statementstmt 77.7% 7 / 9 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 3 / 3 Podpod n/a totaltotal 83.3% 10 / 12 CC 1 SCAR 0.9
CC
1
Cov
78%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
« Build ↑ Summary blib/lib/Geo/Gpx.pm »
1 package Geo::Gpx::Point;
2 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 our $VERSION = '1.08';
6  
7 =encoding utf8
8  
9 =head1 NAME
10  
11 Geo::Gpx::Point - Class to store and edit GPX Waypoints
12  
13 =head1 SYNOPSIS
14  
15 use Geo::Gpx::Point;
16  
17 =head1 DESCRIPTION
18  
19 L<Geo::Gpx::Point> provides a data structure for GPX points and provides accessor methods to read and edit point data.
20  
21 =cut
22  
23 2 ▶use Geo::Gpx;
Subroutine BEGIN: called CC=1 SCAR=2.6
24 use Geo::Coordinates::Transform;
25 use Math::Trig;
26 use Carp qw(confess croak cluck);
27 use Scalar::Util qw( blessed );
28 use vars qw($AUTOLOAD %possible_attr);
29 use overload ('""' => 'as_string');
30  
31 # file-scoped lexicals
32 my @attr = qw/ lat lon ele time magvar geoidheight name cmt desc src link sym type fix sat hdop vdop pdop ageofdgpsdata dgpsid extensions /;
33 $possible_attr{$_} = 1 for @attr;
34  
35 =head2 Constructor Method
36  
37 =over 4
38  
39 =item new( lat => $lat, lon => $lon [, ele => $ele, desc => $desc, … ] )
40  
41 Create and return a new point as per the fields provided, which can be any of C<lat lon ele time magvar geoidheight name cmt desc src link sym type fix sat hdop vdop pdop ageofdgpsdata dgpsid>. Most expect numberial values except: C<name>, C<cmt>, C<desc>, C<src>, C<sym>, C<type>, C<fix> that can contain strings.
42  
43 C<lat> and C<lon> are required, all others keys are optional.
44  
45 %fields = ( lat => 47.0871, lon => 70.9318, ele => 808.000, name => 'MSA', desc => 'A nice view of the River at the top');
46 $pt = Geo::Gpx::Point->new( %fields );
47  
48 The C<link> field is expected to be structured as:
49  
50 link => { href => 'http://hexten.net/', text => 'Hexten', type => 'Blah' },
51  
52 =back
53  
54 =cut
55  
56 sub new {
57 my $proto = shift;
58 my $class = ref($proto) || $proto;
59 my %fields = @_;
60 my $wpt = {};
61 bless( $wpt, $class);
62  
63 foreach my $key ( keys %fields ) {
64 if ( $possible_attr{ $key } ) {
65 $wpt->{ $key } = $fields { $key }
66 } else { croak "field '$key' not supported" }
67 }
68  
69 if (defined $wpt->{time} and $wpt->{time} =~ /-|:/ ) {
70 $wpt->{time} = Geo::Gpx::_time_string_to_epoch( $wpt->{time} )
71 }
72 return $wpt
73 }
74  
75 =over 4
76  
77 =item flex_coordinates( $lat, $lon, %fields )
78  
79 Takes latitude and longitude decimal values or strings and returns a C<Geo::Gpx::Point> object. The latitude should always appear before the longitude and both can be in formatted form (i.e Degrees, Minutes, Seconds or "dms") and the constructor will attempt to convert them to decimals. Any other I<%fields> are optional.
80  
81 $pt = Geo::Gpx::Point->flex_coordinates( '47.0871', '-70.9318', desc => 'Mont Ste-Anne' );
82  
83 If a string reference is passed as the first argument (instead of I<$lat> and I<$lon>), the constructor will attempt to parse it as coordinates (decimal-form only). For instance you can simply call C<< flex_coordinates( '47.0871 -70.9318' ) >> with or without a comma along with optional fields.
84  
85 $str_ref = \'47.0871 -70.9318';
86 $pt = Geo::Gpx::Point->flex_coordinates($str_ref, desc => 'Mont Ste-Anne' );
87  
88 =back
89  
90 =cut
91  
92 sub flex_coordinates {
93 my ($proto, $lat, $lon, %fields) = shift;
94 # objective of this constructor is to be super flexible, for additionl safety do not use
95 # if string ref provided, expect coord in single string (decimal form only I think)
96 if (ref $_[0]) {
97 $lat = shift;
98 $lat = $$lat;
99 $lat =~ s/(,| )+/ /g;
100 ($lat, $lon) = split ' ', $lat;
101 %fields = @_
102 } else { ($lat, $lon, %fields) = @_ }
103 croak 'flex_coordinates takes at least 2 arguments: latitude and longitude'
104 unless ($lon);
105 my $class = ref($proto) || $proto;
106  
107 $lat =~ s/N//; $lon =~ s/N//;
108 $lat =~ s/E//; $lon =~ s/E//;
109 $lat =~ s/S/-/; $lon =~ s/S/-/;
110 $lat =~ s/W/-/; $lon =~ s/W/-/;
111 # convert coord if in DM or DMS format? (they are if whitesp or >2 dots)
112 if ( ( $lat =~ /\d[ \.]+\d+[ \.]/) or
113 ( $lon =~ /\d[ \.]+\d+[ \.]/) ) {
114 my $cnv = new Geo::Coordinates::Transform();
115 my $ref = $cnv->cnv_to_dd( [ $lat, $lon ] );
116 $lat = $ref->[0];
117 $lon = $ref->[1]
118 }
119 return $class->new( lat => $lat, lon => $lon, %fields)
120 }
121  
122 =over 4
123  
124 =item clone()
125  
126 Returns a deep copy of the C<Geo::Gpx::Point>.
127  
128 $clone = $ggp->clone;
129  
130 =back
131  
132 =cut
133  
134 sub clone {
135 my $pt = shift;
136 croak 'clone() expects no arguments' if @_;
137 my %fields;
138 foreach my $key (keys %{$pt}) {
139 $fields{$key} = $pt->{$key}
140 }
141 return $pt->new( %fields )
142 }
143  
144 =head2 AUTOLOAD Methods
145  
146 =over 4
147  
148 =item I<field>( $value )
149  
150 Methods with respect to fields of the object can be autoloaded.
151  
152 Possible fields consist of those listed and accepted by C<new()>, specifically:
153 lat, lon, ele, time, magvar, geoidheight, name, cmt, desc, src, link, sym, type, fix, sat, hdop, vdop, pdop, ageofdgpsdata, and dgpsid.
154  
155 Some fields may contain a value of 0. It is safer to check if a field is defined with C<< if (defined $point->ele) >> rather than C<< if ($point->ele) >>.
156  
157 Caution should be used if setting a I<$value> as no checks are performed to ensure the value is appropriate or in the proper format.
158  
159 =back
160  
161 =cut
162  
163 sub AUTOLOAD {
164 my $self = shift;
165 my $attr = $AUTOLOAD;
166 $attr =~ s/.*:://;
167 return unless $attr =~ /[^A-Z]/; # skip DESTROY and all-cap methods
168 croak "invalid attribute method: -> $attr()" unless $possible_attr{$attr};
169 $self->{$attr} = shift if @_;
170 return $self->{$attr}
171 }
172  
173 =head2 Object Methods
174  
175 =over 4
176  
177 =item distance_to( $pt or lat => $lat, lon => $lon, [ %options ] )
178  
179 Returns the distance in meters from the C<Geo::Gpx::Point> I<$pt> or from the coordinates provided by I<$lat> and I<$lon>. The distance is calculated as the straight-line distance, ignoring any topography. I<$pt> must be the first argument if specified.
180  
181 I<%options> may be any of the following I<key/value> pairs (all optional):
182  
183 Z<> C<< dec => I<$decimals> >>: how many digits to return after the decimal point. Defaults to 6 but this will change to 1 or 2 in the future.
184 Z<> C<< km => I<boole> >>: scale the return value to kilometers rather than meters (default is false).
185 Z<> C<< rad => I<$radius> >>: the earth's radius in kilometers (see below).
186  
187 I<$radius> should rarely be specified unless the user knows what they are doing. The default is the global average of 6371 kilometers and any value outside the 6357 to 6378 range will be ignored. This implies that a given value would affect the returned distance by at most 0.16 percent versus the global average.
188  
189 =back
190  
191 =cut
192  
193 sub distance_to {
194 my $pt = shift;
195  
196 my ($pt_to, %opts);
197 if (blessed $_[0]) {
198 croak 'object as argument must be a Geo::Gpx::Point' unless $_[0]->isa('Geo::Gpx::Point');
199 $pt_to = shift
200 }
201 %opts = @_;
202 $pt_to = Geo::Gpx::Point->new( lat => $opts{lat}, lon => $opts{lon} ) unless $pt_to;
203  
204 my ($radius_default, $radius, $decimal_pts, $scale);
205 $radius_default = 6371;
206 $radius = $opts{rad} || $radius_default;
207 $radius = ($radius < 6357 || $radius > 6378) ? $radius_default : $radius;
208 $decimal_pts = $opts{dec} || 6;
209 $scale = ( $opts{km} ) ? 1 : 1000;
210  
211 my ( $lat1, $lon1, $lat2, $lon2 ) = (
212 Math::Trig::deg2rad( $pt->lat ),
213 Math::Trig::deg2rad( $pt->lon ),
214 Math::Trig::deg2rad( $pt_to->lat ),
215 Math::Trig::deg2rad( $pt_to->lon ),
216 );
217  
218 my $t = sin( ($lat2 - $lat1)/2 ) ** 2 + ( cos( $lat1 ) ** 2 ) * ( sin( ( $lon2 - $lon1 )/2 ) ** 2 );
219 my $d = $radius * ( 2 * atan2( sqrt($t), sqrt(1-$t) ) );
220 return sprintf( "%.${decimal_pts}f", $d * $scale )
221 }
222  
223 =over 4
224  
225 =item to_geocalc()
226  
227 Returns a point as a L<Geo::Calc> object. (Requires that the L<Geo::Calc> module be installed.)
228  
229 =back
230  
231 =cut
232  
233 sub to_geocalc {
234 require Geo::Calc;
235 my $pt = shift;
236 croak "to_geocalc() takes no arguments" if @_;
237 return Geo::Calc->new( lat => $pt->lat, lon => $pt->lon );
238 }
239  
240 =over 4
241  
242 =item to_tcx()
243  
244 Returns a point as a basic L<Geo::TCX::Trackpoint> object, i.e. a point with only Position information. (Requires that the L<Geo::TCX> module be installed.)
245  
246 =back
247  
248 =cut
249  
250 sub to_tcx {
251 require Geo::TCX;
252 my $pt = shift;
253 croak "to_tcx() takes no arguments" if @_;
254 my $xml = '<Position><LatitudeDegrees>' . $pt->lat . '</LatitudeDegrees>' .
255 '<LongitudeDegrees>' . $pt->lon . '</LongitudeDegrees></Position';
256 return Geo::TCX::Trackpoint->new( $xml )
257 }
258  
259 =over 4
260  
261 =item time_datetime ()
262  
263 Return a L<DateTime> object corresponding to the time of the point. The C<time_zone> of the object will be C<< 'UTC' >>. Specify C<< time_zone => $tz >> to set a different one.
264  
265 =back
266  
267 =cut
268  
269 # we never store a DateTime object but provide a method to return one
270 sub time_datetime {
271 my $pt = shift;
272 my %opts = @_;
273 croak 'Geo::Gpx::Point has no time field' unless $pt->time;
274 my $dt = DateTime->from_epoch( epoch => $pt->time );
275 $dt->set_time_zone( $opts{time_zone} ) if $opts{time_zone};
276 return $dt
277 }
278  
279 =over 4
280  
281 =item summ()
282  
283 For debugging purposes mostly. Summarizes the fields of point by printing to screen. Returns nothing.
284  
285 =back
286  
287 =cut
288  
289 sub summ {
290 my $pt = shift;
291 croak 'summ() expects no arguments' if @_;
292 my %fields;
293 foreach my $key (keys %{$pt}) {
294 print "$key: ", $pt->{$key}, "\n"
295 }
296 return undef
297 }
298  
299 =over 4
300  
301 =item as_string()
302  
303 Returns a string with the coordinates e.g. C<lat="47.0871" lon="-70.9318">.
304  
305 =back
306  
307 =cut
308  
309 sub as_string {
310 my $pt = shift;
311 my %fields;
312 my $str;
313 $str = 'lat="' . $pt->{lat} . '" ';
314 $str .= 'lon="' . $pt->{lon} . '"';
315 return $str
316 }
317  
318 =head2 Overloaded Methods
319  
320 C<as_string()> is called when using a C<Geo::Gpx::Point> instance as a string.
321  
322 =head1 EXAMPLES
323  
324 Coming soon.
325  
326 =head1 AUTHOR
327  
328 Patrick Joly C<< <patjol@cpan.org> >>.
329  
330 =head1 VERSION
331  
332 1.08
333  
334 =head1 SEE ALSO
335  
336 perl(1).
337  
338 =cut
339  
340 1;
341  
« Build ↑ Summary blib/lib/Geo/Gpx.pm »