File Coverage

blib/lib/Geo/Distance.pm
Criterion Covered Total %
statement 122 177 68.9
branch 20 46 43.4
condition 20 44 45.4
subroutine 13 14 92.8
pod 5 6 83.3
total 180 287 62.7


line stmt bran cond sub pod time code
1             package Geo::Distance;
2 4     4   888723 use 5.008001;
  4         35  
3 4     4   22 use strict;
  4         7  
  4         78  
4 4     4   20 use warnings;
  4         6  
  4         194  
5             our $VERSION = '0.24';
6              
7             =encoding utf8
8              
9             =head1 NAME
10              
11             Geo::Distance - Calculate distances and closest locations. (DEPRECATED)
12              
13             =head1 SYNOPSIS
14              
15             use Geo::Distance;
16            
17             my $geo = new Geo::Distance;
18             $geo->formula('hsin');
19            
20             $geo->reg_unit( 'toad_hop', 200120 );
21             $geo->reg_unit( 'frog_hop' => 6 => 'toad_hop' );
22            
23             my $distance = $geo->distance( 'unit_type', $lon1,$lat1 => $lon2,$lat2 );
24            
25             my $locations = $geo->closest(
26             dbh => $dbh,
27             table => $table,
28             lon => $lon,
29             lat => $lat,
30             unit => $unit_type,
31             distance => $dist_in_unit
32             );
33              
34             =head1 DESCRIPTION
35              
36             This perl library aims to provide as many tools to make it as simple as possible to calculate
37             distances between geographic points, and anything that can be derived from that. Currently
38             there is support for finding the closest locations within a specified distance, to find the
39             closest number of points to a specified point, and to do basic point-to-point distance
40             calculations.
41              
42             =head1 DEPRECATED
43              
44             This module has been gutted and is now a wrapper around L, please
45             use that module instead.
46              
47             When switching from this module to L make sure you reverse the
48             coordinates when passing them to L. GIS::Distance takes
49             lat/lon pairs while Geo::Distance takes lon/lat pairs.
50              
51             =head1 STABILITY
52              
53             The interface to Geo::Distance is fairly stable nowadays. If this changes it
54             will be noted here.
55              
56             C<0.21> - All distance calculations are now handled by L.
57              
58             C<0.10> - The closest() method has a changed argument syntax and no longer supports array searches.
59              
60             C<0.09> - Changed the behavior of the reg_unit function.
61              
62             C<0.07> - OO only, and other changes all over.
63              
64             =cut
65              
66 4     4   1790 use GIS::Distance;
  4         147607  
  4         155  
67 4     4   1777 use GIS::Distance::Constants qw( :all );
  4         9796  
  4         624  
68 4     4   33 use Carp qw( croak );
  4         8  
  4         158  
69 4     4   22 use Const::Fast;
  4         7  
  4         20  
70              
71             =head1 FORMULAS
72              
73             C - See L.
74              
75             C - See L.
76              
77             C - See L.
78              
79             C - See L.
80              
81             C - See L.
82              
83             C - See L.
84              
85             C - See L.
86              
87             C - See L.
88              
89             =cut
90              
91             const our %GEO_TO_GIS_FORMULA_MAP => (qw(
92             alt ALT
93             cos Cosine
94             gcd GreatCircle
95             hsin Haversine
96             mt MathTrig
97             null Null
98             polar Polar
99             tv Vincenty
100             ));
101              
102             const our @FORMULAS => (keys %GEO_TO_GIS_FORMULA_MAP);
103              
104             =head1 PROPERTIES
105              
106             =head2 UNITS
107              
108             All functions accept a unit type to do the computations of distance with. By default no units
109             are defined in a Geo::Distance object. You can add units with reg_unit() or create some default
110             units with default_units().
111              
112             =head2 LATITUDE AND LONGITUDE
113              
114             When a function needs a longitude and latitude, they must always be in decimal degree format.
115             Here is some sample code for converting from other formats to decimal:
116              
117             # DMS to Decimal
118             my $decimal = $degrees + ($minutes/60) + ($seconds/3600);
119            
120             # Precision Six Integer to Decimal
121             my $decimal = $integer * .000001;
122              
123             If you want to convert from decimal radians to degrees you can use Math::Trig's rad2deg function.
124              
125             =head1 METHODS
126              
127             =head2 new
128              
129             my $geo = new Geo::Distance;
130             my $geo = new Geo::Distance( no_units=>1 );
131              
132             Returns a blessed Geo::Distance object. The new constructor accepts one optional
133             argument.
134              
135             no_units - Whether or not to load the default units. Defaults to 0 (false).
136             kilometer, kilometre, meter, metre, centimeter, centimetre, millimeter,
137             millimetre, yard, foot, inch, light second, mile, nautical mile,
138             poppy seed, barleycorn, rod, pole, perch, chain, furlong, league,
139             fathom
140              
141             =cut
142              
143             sub new {
144 4     4 1 406 my $class = shift;
145 4         16 my $self = bless {}, $class;
146 4         25 my %args = @_;
147              
148 4         28 $self->{formula} = 'hsin';
149 4         52 $self->{units} = {};
150 4 50       20 if(!$args{no_units}){
151 4         24 $self->reg_unit( $KILOMETER_RHO, 'kilometer' );
152 4         27 $self->reg_unit( 1000, 'meter', => 'kilometer' );
153 4         16 $self->reg_unit( 100, 'centimeter' => 'meter' );
154 4         16 $self->reg_unit( 10, 'millimeter' => 'centimeter' );
155              
156 4         16 $self->reg_unit( 'kilometre' => 'kilometer' );
157 4         13 $self->reg_unit( 'metre' => 'meter' );
158 4         13 $self->reg_unit( 'centimetre' => 'centimeter' );
159 4         14 $self->reg_unit( 'millimetre' => 'millimeter' );
160              
161 4         14 $self->reg_unit( 'mile' => 1609.344, 'meter' );
162 4         15 $self->reg_unit( 'nautical mile' => 1852, 'meter' );
163 4         13 $self->reg_unit( 'yard' => 0.9144, 'meter' );
164 4         15 $self->reg_unit( 3, 'foot' => 'yard' );
165 4         15 $self->reg_unit( 12, 'inch' => 'foot' );
166 4         14 $self->reg_unit( 'light second' => 299792458, 'meter' );
167              
168 4         16 $self->reg_unit( 'poppy seed' => 2.11, 'millimeter' );
169 4         14 $self->reg_unit( 'barleycorn' => 8.467, 'millimeter' );
170 4         14 $self->reg_unit( 'rod' => 5.0292, 'meter' );
171 4         13 $self->reg_unit( 'pole' => 'rod' );
172 4         12 $self->reg_unit( 'perch' => 'rod' );
173 4         14 $self->reg_unit( 'chain' => 20.1168, 'meter' );
174 4         14 $self->reg_unit( 'furlong' => 201.168, 'meter' );
175 4         16 $self->reg_unit( 'league' => 4.828032, 'kilometer' );
176 4         10 $self->reg_unit( 1.8288, 'fathom' => 'meter' );
177             }
178              
179 4         17 return $self;
180             }
181              
182             =head2 formula
183              
184             if($geo->formula eq 'hsin'){ ... }
185             $geo->formula('cos');
186              
187             Allows you to retrieve and set the formula that is currently being used to
188             calculate distances. See the available L.
189              
190             C is the default. Both C and C are inferior in speed
191             and accuracy to C.
192              
193             =cut
194              
195             sub formula {
196 2     2 1 523 my $self = shift;
197              
198 2 50       7 return $self->{formula} if !$_[0];
199 2         4 my $formula = shift;
200              
201 2         6 my $gis_formula = $GEO_TO_GIS_FORMULA_MAP{ $formula };
202              
203 2 50       7 croak(
204             'Unknown formula (available formulas are ',
205             join(', ', sort @FORMULAS),
206             ')',
207             ) if !$gis_formula;
208              
209 2         3 $self->{formula} = $formula;
210 2         4 $self->{gis_formula} = $gis_formula;
211              
212 2         4 return $formula;
213             }
214              
215             =head2 reg_unit
216              
217             $geo->reg_unit( $radius, $key );
218             $geo->reg_unit( $key1 => $key2 );
219             $geo->reg_unit( $count1, $key1 => $key2 );
220             $geo->reg_unit( $key1 => $count2, $key2 );
221             $geo->reg_unit( $count1, $key1 => $count2, $key2 );
222              
223             This method is used to create custom unit types. There are several ways of calling it,
224             depending on if you are defining the unit from scratch, or if you are basing it off
225             of an existing unit (such as saying 12 inches = 1 foot ). When defining a unit from
226             scratch you pass the name and rho (radius of the earth in that unit) value.
227              
228             So, if you wanted to do your calculations in human adult steps you would have to have an
229             average human adult walk from the crust of the earth to the core (ignore the fact that
230             this is impossible). So, assuming we did this and we came up with 43,200 steps, you'd
231             do something like the following.
232              
233             # Define adult step unit.
234             $geo->reg_unit( 43200, 'adult step' );
235             # This can be read as "It takes 43,200 adult_steps to walk the radius of the earth".
236              
237             Now, if you also wanted to do distances in baby steps you might think "well, now I
238             gotta get a baby to walk to the center of the earth". But, you don't have to! If you do some
239             research you'll find (no research was actually conducted) that there are, on average,
240             4.7 baby steps in each adult step.
241              
242             # Define baby step unit.
243             $geo->reg_unit( 4.7, 'baby step' => 'adult step' );
244             # This can be read as "4.7 baby steps is the same as one adult step".
245              
246             And if we were doing this in reverse and already had the baby step unit but not
247             the adult step, you would still use the exact same syntax as above.
248              
249             =cut
250              
251             sub reg_unit {
252 92     92 1 125 my $self = shift;
253 92         115 my $units = $self->{units};
254 92         148 my($count1,$key1,$count2,$key2);
255 92         131 $count1 = shift;
256 92 100 66     346 if($count1=~/[^\.0-9]/ or !@_){ $key1=$count1; $count1=1; }
  64         95  
  64         83  
257 28         49 else{ $key1 = shift; }
258 92 100       163 if(!@_){
259 4         16 $units->{$key1} = $count1;
260             }else{
261 88         124 $count2 = shift;
262 88 100 66     323 if($count2=~/[^\.0-9]/ or !@_){ $key2=$count2; $count2=1; }
  48         83  
  48         59  
263 40         59 else{ $key2 = shift; }
264 88 50       175 ($key1,$key2) = ($key2,$key1) if( defined $units->{$key1} );
265 88         256 $units->{$key1} = ($units->{$key2}*$count1) / $count2;
266             }
267             }
268              
269             =head2 distance
270              
271             my $distance = $geo->distance( 'unit_type', $lon1,$lat1 => $lon2,$lat2 );
272              
273             Calculates the distance between two lon/lat points.
274              
275             =cut
276              
277             sub distance {
278 39     39 1 145 my ($self, $unit, $lon1, $lat1, $lon2, $lat2) = @_;
279              
280 39         62 my $unit_rho = $self->{units}->{$unit};
281 39 50       133 croak('Unkown unit type "' . $unit . '"') if !$unit_rho;
282              
283 39         170 my $gis = GIS::Distance->new( $self->{gis_formula} );
284              
285             # Reverse lon/lat to lat/lon, the way GIS::Distance wants it.
286 39         10903 my $km = $gis->{code}->( $lat1, $lon1, $lat2, $lon2 );
287              
288 39         1500 return $km * ($unit_rho / $KILOMETER_RHO);
289             }
290              
291 4     4   5311 use Math::Trig qw( acos asin atan deg2rad great_circle_distance pi tan );
  4         54580  
  4         5236  
292              
293             sub old_distance {
294 0     0 0 0 my($self,$unit,$lon1,$lat1,$lon2,$lat2) = @_;
295 0 0       0 croak('Unkown unit type "'.$unit.'"') unless($unit = $self->{units}->{$unit});
296              
297 0 0       0 return 0 if $self->{formula} eq 'null';
298              
299 0 0       0 if($self->{formula} eq 'mt'){
300 0         0 return great_circle_distance(
301             deg2rad($lon1),
302             deg2rad(90 - $lat1),
303             deg2rad($lon2),
304             deg2rad(90 - $lat2),
305             $unit
306             );
307             }
308              
309 0         0 $lon1 = deg2rad($lon1); $lat1 = deg2rad($lat1);
  0         0  
310 0         0 $lon2 = deg2rad($lon2); $lat2 = deg2rad($lat2);
  0         0  
311 0         0 my $c;
312 0 0       0 if($self->{formula} eq 'cos'){
    0          
    0          
    0          
    0          
313 0         0 my $a = sin($lat1) * sin($lat2);
314 0         0 my $b = cos($lat1) * cos($lat2) * cos($lon2 - $lon1);
315 0         0 $c = acos($a + $b);
316             }
317             elsif($self->{formula} eq 'hsin'){
318 0         0 my $dlon = $lon2 - $lon1;
319 0         0 my $dlat = $lat2 - $lat1;
320 0         0 my $a = (sin($dlat/2)) ** 2 + cos($lat1) * cos($lat2) * (sin($dlon/2)) ** 2;
321 0         0 $c = 2 * atan2(sqrt($a), sqrt(abs(1-$a)));
322             }
323             elsif($self->{formula} eq 'polar'){
324 0         0 my $a = pi/2 - $lat1;
325 0         0 my $b = pi/2 - $lat2;
326 0         0 $c = sqrt( $a ** 2 + $b ** 2 - 2 * $a * $b * cos($lon2 - $lon1) );
327             }
328             elsif($self->{formula} eq 'gcd'){
329 0         0 $c = 2*asin( sqrt(
330             ( sin(($lat1-$lat2)/2) )**2 +
331             cos($lat1) * cos($lat2) *
332             ( sin(($lon1-$lon2)/2) )**2
333             ) );
334              
335             # Eric Samuelson recommended this formula.
336             # http://forums.devshed.com/t54655/sc3d021a264676b9b440ea7cbe1f775a1.html
337             # http://williams.best.vwh.net/avform.htm
338             # It seems to produce the same results at the hsin formula, so...
339              
340             #my $dlon = $lon2 - $lon1;
341             #my $dlat = $lat2 - $lat1;
342             #my $a = (sin($dlat / 2)) ** 2
343             # + cos($lat1) * cos($lat2) * (sin($dlon / 2)) ** 2;
344             #$c = 2 * atan2(sqrt($a), sqrt(1 - $a));
345             }
346             elsif($self->{formula} eq 'tv'){
347 0         0 my($a,$b,$f) = (6378137,6356752.3142,1/298.257223563);
348 0         0 my $l = $lon2 - $lon1;
349 0         0 my $u1 = atan((1-$f) * tan($lat1));
350 0         0 my $u2 = atan((1-$f) * tan($lat2));
351 0         0 my $sin_u1 = sin($u1); my $cos_u1 = cos($u1);
  0         0  
352 0         0 my $sin_u2 = sin($u2); my $cos_u2 = cos($u2);
  0         0  
353 0         0 my $lambda = $l;
354 0         0 my $lambda_pi = 2 * pi;
355 0         0 my $iter_limit = 20;
356 0         0 my($cos_sq_alpha,$sin_sigma,$cos2sigma_m,$cos_sigma,$sigma);
357 0   0     0 while( abs($lambda-$lambda_pi) > 1e-12 && --$iter_limit>0 ){
358 0         0 my $sin_lambda = sin($lambda); my $cos_lambda = cos($lambda);
  0         0  
359 0         0 $sin_sigma = sqrt(($cos_u2*$sin_lambda) * ($cos_u2*$sin_lambda) +
360             ($cos_u1*$sin_u2-$sin_u1*$cos_u2*$cos_lambda) * ($cos_u1*$sin_u2-$sin_u1*$cos_u2*$cos_lambda));
361 0         0 $cos_sigma = $sin_u1*$sin_u2 + $cos_u1*$cos_u2*$cos_lambda;
362 0         0 $sigma = atan2($sin_sigma, $cos_sigma);
363 0         0 my $alpha = asin($cos_u1 * $cos_u2 * $sin_lambda / $sin_sigma);
364 0         0 $cos_sq_alpha = cos($alpha) * cos($alpha);
365 0         0 $cos2sigma_m = $cos_sigma - 2*$sin_u1*$sin_u2/$cos_sq_alpha;
366 0         0 my $cc = $f/16*$cos_sq_alpha*(4+$f*(4-3*$cos_sq_alpha));
367 0         0 $lambda_pi = $lambda;
368 0         0 $lambda = $l + (1-$cc) * $f * sin($alpha) *
369             ($sigma + $cc*$sin_sigma*($cos2sigma_m+$cc*$cos_sigma*(-1+2*$cos2sigma_m*$cos2sigma_m)));
370             }
371 0 0       0 undef if( $iter_limit==0 );
372 0         0 my $usq = $cos_sq_alpha*($a*$a-$b*$b)/($b*$b);
373 0         0 my $aa = 1 + $usq/16384*(4096+$usq*(-768+$usq*(320-175*$usq)));
374 0         0 my $bb = $usq/1024 * (256+$usq*(-128+$usq*(74-47*$usq)));
375 0         0 my $delta_sigma = $bb*$sin_sigma*($cos2sigma_m+$bb/4*($cos_sigma*(-1+2*$cos2sigma_m*$cos2sigma_m)-
376             $bb/6*$cos2sigma_m*(-3+4*$sin_sigma*$sin_sigma)*(-3+4*$cos2sigma_m*$cos2sigma_m)));
377 0         0 $c = ( $b*$aa*($sigma-$delta_sigma) ) / $self->{units}->{meter};
378             }
379             else{
380 0         0 croak('Unkown distance formula "'.$self->{formula}.'"');
381             }
382              
383 0         0 return $unit * $c;
384             }
385              
386             =head2 closest
387              
388             my $locations = $geo->closest(
389             dbh => $dbh,
390             table => $table,
391             lon => $lon,
392             lat => $lat,
393             unit => $unit_type,
394             distance => $dist_in_unit
395             );
396              
397             This method finds the closest locations within a certain distance and returns an
398             array reference with a hash for each location matched.
399              
400             The closest method requires the following arguments:
401              
402             dbh - a DBI database handle
403             table - a table within dbh that contains the locations to search
404             lon - the longitude of the center point
405             lat - the latitude of the center point
406             unit - the unit of measurement to use, such as "meter"
407             distance - the distance, in units, from the center point to find locations
408              
409             The following arguments are optional:
410              
411             lon_field - the name of the field in the table that contains the longitude, defaults to "lon"
412             lat_field - the name of the field in the table that contains the latitude, defaults to "lat"
413             fields - an array reference of extra field names that you would like returned with each location
414             where - additional rules for the where clause of the sql
415             bind - an array reference of bind variables to go with the placeholders in where
416             sort - whether to sort the locations by their distance, making the closest location the first returned
417             count - return at most these number of locations (implies sort => 1)
418              
419             This method uses some very simplistic calculations to SQL select out of the dbh. This
420             means that the SQL should work fine on almost any database (only tested on MySQL and SQLite so far) and
421             this also means that it is fast. Once this sub set of locations has been retrieved
422             then more precise calculations are made to narrow down the result set. Remember, though, that
423             the farther out your distance is, and the more locations in the table, the slower your searches will be.
424              
425             =cut
426              
427             sub closest {
428 4     4 1 10040 my $self = shift;
429 4         30 my %args = @_;
430              
431             # Set defaults and prepare.
432 4   33     15 my $dbh = $args{dbh} || croak('You must supply a database handle');
433 4 50       23 $dbh->isa('DBI::db') || croak('The dbh must be a DBI database handle');
434 4   33     14 my $table = $args{table} || croak('You must supply a table name');
435 4   33     10 my $lon = $args{lon} || croak('You must supply a longitude');
436 4   33     9 my $lat = $args{lat} || croak('You must supply a latitude');
437 4   33     10 my $distance = $args{distance} || croak('You must supply a distance');
438 4   33     9 my $unit = $args{unit} || croak('You must specify a unit type');
439 4   33     14 my $unit_size = $self->{units}->{$unit} || croak('This unit type is not known');
440 4         18 my $degrees = $distance / ( $DEG_RATIO * $unit_size );
441 4   50     20 my $lon_field = $args{lon_field} || 'lon';
442 4   50     15 my $lat_field = $args{lat_field} || 'lat';
443 4   50     15 my $fields = $args{fields} || [];
444              
445 4         12 unshift @$fields, $lon_field, $lat_field;
446 4         13 $fields = join( ',', @$fields );
447 4   100     17 my $count = $args{count} || 0;
448 4   66     18 my $sort = $args{sort} || ( $count ? 1 : 0 );
449 4         14 my $where = qq{$lon_field >= ? AND $lat_field >= ? AND $lon_field <= ? AND $lat_field <= ?};
450 4 50       10 $where .= ( $args{where} ? " AND ($args{where})" : '' );
451              
452             my @bind = (
453             $lon-$degrees, $lat-$degrees,
454             $lon+$degrees, $lat+$degrees,
455 4 50       27 ( $args{bind} ? @{$args{bind}} : () )
  0         0  
456             );
457              
458             # Retrieve locations.
459 4         38 my $sth = $dbh->prepare(qq{
460             SELECT $fields
461             FROM $table
462             WHERE $where
463             });
464 4         489 $sth->execute( @bind );
465 4         11 my $locations = [];
466 4         97 while(my $location = $sth->fetchrow_hashref){
467 35         397 push @$locations, $location;
468             }
469              
470             # Calculate distances.
471 4         12 my $closest = [];
472 4         11 foreach my $location (@$locations){
473             $location->{distance} = $self->distance(
474             $unit, $lon, $lat,
475             $location->{$lon_field},
476 35         84 $location->{$lat_field}
477             );
478 35 100       81 if( $location->{distance} <= $distance ){
479 32         63 push @$closest, $location;
480             }
481             }
482 4         10 $locations = $closest;
483              
484             # Sort.
485 4 100       11 if( $sort ){
486 1         8 @$locations = sort { $a->{distance} <=> $b->{distance} } @$locations;
  17         29  
487             }
488              
489             # Split for count.
490 4 100 66     17 if( $count and $count < @$locations ){
491 1         6 splice @$locations, $count;
492             }
493              
494 4         81 return $locations;
495             }
496              
497             1;
498             __END__