This time, I'll post it to the list:

> From: Lee Goddard [mailto:[EMAIL PROTECTED]]
> Subject: Re: Distance between 2 latitudes and longitudes

> At 10:14 06/03/2002 -0600, MOTTER, JEFFREY D. wrote:
> >Does any know where I can find a script to calculate the 
> distance between 2
> >seperate latitudes and longitudes?


I must have missed the original post.  There are actually a couple of
different methods for determining the distance between 2 long/lat pairs and
you need to be aware of the accuracy of each. The Great Circle method is the
least accurate IIRC, but is the most accessible, as it is a part of
Math::Trig.  

I wrote some code to do this using the various methods. Actually, it finds
the distances between two zip codes for which the long/lat pairs are known,
but I'll remove the database stuff for you and just give the pertinent code.

You should also read:

http://www.chilidog.com/zip/zipnotes.html
http://mathforum.org/dr.math/problems/neff.04.21.99.html

and my favorite:

http://op.gfz-potsdam.de/GMT-Help/Archive/msg00143.html

<CODE>

use Math::Trig qw(deg2rad pi great_circle_distance asin acos);

                      
my ($lat1, $long1);
my ($lat2, $long2);

print "Haversine   : ". &Haversine($lat1, $long1, $lat2, $long2) ."\n";
print "Law Cosines : ". &LawCosines($lat1, $long1, $lat2, $long2)."\n";
print "Flat-Earth  : ". &FlatEarth($lat1, $long1, $lat2, $long2) ."\n";
print "Great Circle: ". &GreatCircle($lat1, $long1, $lat2, $long2)."\n";
                   

sub LawCosines {
my ($lat1, $long1, $lat2, $long2) = @_;
my $r=3956;

my $dist = acos(sin(deg2rad($lat1))*
                sin(deg2rad($lat2))+
                cos(deg2rad($lat1))*
                cos(deg2rad($lat2))*
                cos(deg2rad($long2)- deg2rad($long1))) * $r;
return $dist;

}

sub FlatEarth {
    my ($lat1, $long1, $lat2, $long2) = @_;
    my $r=3956;

    my $a = (pi/2)- deg2rad($lat1);               
    my $b = (pi/2)- deg2rad($lat2);
    my $c = sqrt($a**2 + $b**2 - 2 * $a *$b
*cos(deg2rad($long2)-deg2rad($long1)));
    my $dist = $c * $r;

return $dist;

}

sub Haversine {
my ($lat1, $long1, $lat2, $long2) = @_;
my $r=3956;

               
$dlong = deg2rad($long1) - deg2rad($long2);
$dlat  = deg2rad($lat1) - deg2rad($lat2);

$a = sin($dlat/2)**2 +cos(deg2rad($lat1)) 
                    * cos(deg2rad($lat2))
                    * sin($dlong/2)**2;
$c = 2 * (asin(sqrt($a)));
$dist = $r * $c;               


return $dist;

}

sub GreatCircle {
my ($lat1, $long1, $lat2, $long2) = @_;
my $r=3956;
    my @zip1 = (deg2rad($long1), deg2rad(90-$lat1));
    my @zip2 = (deg2rad($long2), deg2rad(90-$lat2));
    my $dist = great_circle_distance(@zip1, @zip2,$r);
                     

return $dist;

}

</CODE>

Hope that helps.

Chuck.
_______________________________________________
Perl-Win32-Users mailing list
[EMAIL PROTECTED]
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs

Reply via email to