I'm prototyping some code that I'll eventually port over to C for an Arduino project I've been working on (much quicker to prototype in Perl first) and am hoping for some feedback from the mathematicians.
So the code is designed to calculate a direction in compass degrees between two sets of GPS coordinates, then convert that degree into a compass direction. The following example is between Calgary, AB, Canada to Toronto, ON, Canada. From what I've found on the Internet, this direction is approximately 94 degrees, which the code outputs correctly.
I completely comprehend and had no problem at all writing the direction() function, but had to do a lot of reading and guessing with the trig stuff in bearing() as it's much beyond my mathematical understanding, and am wondering if it appears reasonably sane.
use warnings; use strict; use Math::Trig; use constant PI => 3.14159265358979; # calgary my $lat1 = 51.32055555555556; my $lon1 = -114.7297222222222221; # toronto my $lat2 = 43.65321111111111; my $lon2 = -79.38321111111111; my $bearing = bearing($lat1, $lon1, $lat2, $lon2); my $direction = direction($bearing); print "$bearing, $direction\n"; sub bearing { my ($lat1, $lon1, $lat2, $lon2) = map { ($_ * PI) / 180 } @_; my $d_lon = $lon2 - $lon1; my $y = sin($d_lon) * cos($lat2); my $x = cos($lat1) * sin($lat2) - sin($lat1) * cos($lat2) * cos($d_lon); my $rad = atan2($y, $x); my $deg = $rad * (180 / PI); return $deg < 0 ? $deg += 360 : $deg; } sub direction { my ($deg) = @_; my @directions = qw( N NNE NE ENE E ESE SE SSE S SSW SW WSW W WNW NW NNW N ); my $calc = (($deg % 360) / 22.5) + .5; return $directions[$calc]; } __END__ 94.0048844699519, E
In reply to Calculate bearing between GPS coordinates by stevieb
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |