Solved
PHP function to calculate bearing between latitudes and longitudes
Posted on 2004-08-15
I need to be able to calculate the bearing between two latitude and longitude pairs, in PHP. They are decimal degrees, and since we are in Australia, our points we are working with are negative latitude, positive longitude. eg. -29.54546 Latitude and 149.68756 longitude.
I have tried this:
$bearingradians = atan2(asin($long1-$long2)*cos($lat2),
cos($lat1)*sin($lat2) - sin($lat1)*cos($lat2)*cos($long1-$long2));
$bearingdegrees = rad2deg($bearing);
This seems to work, but on closer inspection, it gets east and west mixed up! ie: When I know that a point should be west of a certain point, it comes up with say, 88degrees, which is obviously east! I am putting the lats and longs around the right way, so thats not the problem. I am trying to make a function which will take the four numbers and spit out the bearing between them, like this:
function bearing($lat1, $long1, $lat2, $long2){
$bearingradians = atan2(asin($long1-$long2)*cos($lat2),
cos($lat1)*sin($lat2) - sin($lat1)*cos($lat2)*cos($long1-$long2));
$bearingdegrees = rad2deg($bearing);
return $bearingdegrees
}
Can anyone see what im doing wrong mathematically? I need this working asap...