# PHP Lat Lng Distance and Bearing

Jun 10th, 2021 (edited)
165
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. <?php
2. \$DEG2RAD = 3.14159265359 / 180;
4. function distbear( \$a, \$b ){
5.     // distance and bearing at point \$a to go to point \$b
8.     \$_a = pow( sin( 0.5 * ( \$b->lat - \$a->lat ) ), 2 ) +
9.         cos( \$b->lat ) * cos( \$a->lat ) * pow( sin( 0.5 * ( \$b->lng - \$a->lng ) ), 2 );
10.     \$_d = \$EARTHRAD * 2 * atan2( sqrt( \$_a ), sqrt( 1 - \$_a ) );
11.     \$_n = cos( \$a->lat ) * sin( \$b->lat ) - sin( \$a->lat ) * cos( \$b->lat ) * cos( \$b->lng - \$a->lng ); //north
12.     \$_e = sin( \$b->lng - \$a->lng ) * cos( \$b->lat ); //east
13.     \$_b = atan2( \$_e, \$_n ); // FORMULA: bear = atan2( 90deg=east, 0deg=north ) //south=-north, west=-east
14.     return (object) array( 'distance'=>\$_d, 'bearing'=>\$_b );
15. }
16. \$a = (object) array('lat' => \$DEG2RAD * +0.0000, 'lng' => \$DEG2RAD * +0.0000 );
17. \$b = (object) array('lat' => \$DEG2RAD * +0.0000, 'lng' => \$DEG2RAD * -1.0000 ); // west
18. \$b = (object) array('lat' => \$DEG2RAD * +0.0000, 'lng' => \$DEG2RAD * +1.0000 ); // east
19. \$b = (object) array('lat' => \$DEG2RAD * +1.0000, 'lng' => \$DEG2RAD * +0.0000 ); // north
20. \$b = (object) array('lat' => \$DEG2RAD * -1.0000, 'lng' => \$DEG2RAD * +0.0000 ); // south
21. print_r( distbear( \$a, \$b ) );
RAW Paste Data