On Aug 29, 2012, at 2:08 PM, Chris Stinemetz wrote:

> Hello List,
> 
> I'm tyring to find the distance in miles between two sets of
> coordinates by using the module Math::Trig
> 
> I'm expecting the return distance to be around 16.91 miles.
> 
> Any help is greatly appriciated.
> 
> Chris
> 
> #!/usr/bin/perl
> 
> use strict;
> use warnings;
> use Math::Trig qw(pi great_circle_distance);
> 
> my $LAT1 = 39.316858;
> my $LAT2 = 39.243556;
> my $LONG1 = -94.963194;
> my $LONG2 = -94.6617;
> print great_circle_distance($LONG1, pi/2 - $LAT1, $LONG2, pi/2 - $LAT2);

The Math::Trig routines all work with radians. Therefore, you are going to have 
to convert your locations from degrees to radians. You can use the 
Math::Trig::deg2rad function. Note that pi/2 is radians, so you are subtracting 
degrees from radians, which never works.

The great_circle_distance function returns radians by default, so you are going 
to have to convert the return values into miles using the approximate radius of 
the earth in miles (~3963mi). Note that the earth is not a perfect sphere, so 
it doesn't have just one radius, but varies from pole to equator.

If you want to do latitude, longitude, and distance calculations, there are 
modules available from CPAN. I can mention Geo::Distance, GIS::Distance, and 
Geo::Ellipsoid (which I wrote). These modules take into account the fact that 
the earth not perfectly spherical.

Here is your program modified to compare results from Geo::Ellipsoid and 
Math::Trig::great_circle_distance.

#!/usr/bin/perl

use strict;
use warnings;
use feature qw(say);
use Math::Trig qw(pi great_circle_distance deg2rad);
use Geo::Ellipsoid;

my $earth_meters = 6378137.0;
my $meters_per_mile = 1609.34;
my $earth_miles = $earth_meters / $meters_per_mile;
say "The radius of the earth is $earth_miles miles";

my $lat1 = 39.316858;
my $lat2 = 39.243556;
my $lon1 = -94.963194;
my $lon2 = -94.6617;

my $latrad1 = deg2rad($lat1);
my $latrad2 = deg2rad($lat2);
my $lonrad1 = deg2rad($lon1);
my $lonrad2 = deg2rad($lon2);

my $dist = great_circle_distance($lonrad1, pi/2 - $latrad1, $lonrad2, pi/2 - 
$latrad2);
say $dist * $earth_meters / $meters_per_mile;

my $ellipsoid = Geo::Ellipsoid->new(units=>'degrees', dist=>'miles');
say $ellipsoid->range($lat1,$lon1,$lat2,$lon2);


Results:

The radius of the earth is 3963.20044241739 miles
16.9202528447011
16.9368500188459




--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to