Wednesday, November 23, 2011

Computing the distance between zip codes longitude / latitude

I have created a function that will compute for the distance between zip codes (longitude / latitude).

The function will actually go a series of conversion from degrees to radians, radians to degrees, degrees to miles, then miles to any unit of measurement you want.

For the benefit of this post, we will have the distance in kilometers.

Given that, we need the multipliers below.

my $pi = atan2(1,1) * 4; # pi: 3.14159265358979
my $deg2radmul = $pi / 180; # degrees to radians multiplier: 0.0174532925199433
my $rad2degmul = 180 / $pi; # radians to degrees multiplier: 57.2957795130823
my $deg2milmul = 69.09; # degrees to miles multiplier
my $mil2kilmul = 1.609344; # miles to kilometers multiplier


First, we have to get the distance between longitude1 and longitude2 by subtracting the two points.

my $dlon = $lon1 - $lon2;


Next, get the distance by getting the radians value of each points and use sin and cos function in perl.

my $dist = sin($lat1 * $deg2radmul) * sin($lat2 * $deg2radmul) + cos($lat1 * $deg2radmul) * cos($lat2 * $deg2radmul) * cos($dlon * $deg2radmul);


Then finally, convert the distance in radians, radians to degrees, degrees to miles, and miles to kilometers.

$dist = atan2(sqrt(1 - $dist**2), $dist);
$dist = $dist * $rad2degmul; # radians to degrees
$dist = $dist * $deg2milmul; # degrees to miles
$dist = $dist * $mil2kilmul; # miles to kilometers


To get the complete implementation and example that I created, please see below. Happy Coding!

#!/usr/bin/perl

my $lat1 = '14.559943';
my $lon1 = '121.015198';
my $lat2 = '14.56255';
my $lon2 = '121.017151';

my $dist = &distance($lat1, $lon1, $lat2, $lon2);
print "distance in km: $dist\n";

#!/usr/bin/perl

my $lat1 = '14.559943';
my $lon1 = '121.015198';
my $lat2 = '14.56255';
my $lon2 = '121.017151';

my $dist = &distance($lat1, $lon1, $lat2, $lon2);
print "distance in km: $dist\n";

sub distance
{
  my ($lat1, $lon1, $lat2, $lon2) = @_;
  my ($pi, $deg2radmul, $rad2degmul, $deg2milmul, $mil2kilmul, $dlon, $dist);

  $pi = atan2(1,1) * 4; # pi: 3.14159265358979
  $deg2radmul = $pi / 180; # degrees to radians multiplier: 0.0174532925199433
  $rad2degmul = 180 / $pi; # radians to degrees multiplier: 57.2957795130823
  $deg2milmul = 69.09; # degrees to miles multiplier
  $mil2kilmul = 1.609344; # miles to kilometers multiplier

  $dlon = $lon1 - $lon2;
  $dist = sin($lat1 * $deg2radmul) * sin($lat2 * $deg2radmul) + cos($lat1 * $deg2radmul) * cos($lat2 * $deg2radmul) * cos($dlon * $deg2radmul);

  $dist = atan2(sqrt(1 - $dist**2), $dist);
  $dist = $dist * $rad2degmul; # radians to degrees
  $dist = $dist * $deg2milmul; # degrees to miles
  $dist = $dist * $mil2kilmul; # miles to kilometers

  return ($dist);
}




1;


Some men succeed by what they know; some by what they do; and a few by what they are.

No comments:

Post a Comment