PHP is like "Perl light" so it translates almost one-on-one (as an exercise try to spot the differences and understand why they are different):
use strict;
sub distance {
my ( $lat1, $lon1, $lat2, $lon2, $unit ) = @_;
my $theta = $lon1 - $lon2;
my $dist
= sin( deg2rad($lat1) ) * sin( deg2rad($lat2) )
+ cos( deg2rad($lat1) ) * cos( deg2rad($lat2) ) *
cos( deg2rad($theta) );
$dist = acos($dist);
$dist = rad2deg($dist);
my $miles = $dist * 60 * 1.1515;
$unit = uc $unit;
if ( $unit eq "K" ) {
return ( $miles * 1.609344 );
} ## end if ( $unit eq "K" )
elsif ( $unit eq "N" ) {
return ( $miles * 0.8684 );
} ## end elsif ( $unit eq "N" )
else {
return $miles;
} ## end else [ if ( $unit eq "K" )
} ## end sub distance
sub acos { atan2( sqrt( 1 - $_[0] * $_[0] ), $_[0] ) }
sub deg2rad { $_[0] * 0.0174532925 }
sub rad2deg { $_[0] * 57.2957795 }
print distance(60.1843160, -128.5069940, 29.46786, -98.53506, "M"), "
+miles\n";
print distance(32.9697, -96.80322, 29.46786, -98.53506, "K"), " kilome
+ters\n";
print distance(32.9697, -96.80322, 29.46786, -98.53506, "N"), " nautic
+al miles\n";
gives as output:
2535.33852270174 miles
422.738930838725 kilometers
228.109395841006 nautical miles
To be entirely correct you probably want to limit the number of decimals as so many decimals will not all be significant.
And if you go all the way and make use of the existing modules at CPAN:
use GIS::Distance;
my $gis = GIS::Distance->new();
$gis->formula('Cosine');
print $gis->distance( 60.1843160, -128.5069940 => 29.46786, -98.53506
+)
->value('mile'), " miles\n";
print $gis->distance( 32.9697, -96.80322 => 29.46786, -98.53506 )
->value('kilometer'), " kilometers\n";
print $gis->distance( 32.9697, -96.80322 => 29.46786, -98.53506 )
->value('nautical_mile'), " nautical miles\n";
CountZero
A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James