fork(1) download
  1. <?php
  2.  
  3. const R = 6371; // km
  4.  
  5. function distance_between_points_rad($lat1, $lng1, $lat2, $lng2){
  6. // latlng in radians
  7. $x = ($lng2-$lng1) * cos(($lat1+$lat2)/2);
  8. $y = ($lat2-$lat1);
  9. // return distance in km
  10. return sqrt($x*$x + $y*$y) * R;
  11. }
  12.  
  13. function get_destination_lat_rad($lat1, $lng1, $d, $brng){
  14. return asin( sin($lat1)*cos($d/R) +
  15. cos($lat1)*sin($d/R)*cos($brng) );
  16. }
  17.  
  18. function get_destination_lng_rad($lat1, $lng1, $d, $brng){
  19. $lat2 = get_destination_lat_rad($lat1, $lng1, $d, $brng);
  20. return $lng1 + atan2(sin($brng)*sin($d/R)*cos($lat1),
  21. cos($d/R)-sin($lat1)*sin($lat2));
  22. }
  23.  
  24. function get_bounding_box_rad($lat, $lng, $range){
  25. // latlng in radians, $range in km
  26. $latmin = get_destination_lat_rad($lat, $lng, $range, 0);
  27. $latmax = get_destination_lat_rad($lat, $lng, $range, deg2rad(180));
  28. $lngmax = get_destination_lng_rad($lat, $lng, $range, deg2rad(90));
  29. $lngmin = get_destination_lng_rad($lat, $lng, $range, deg2rad(270));
  30. // return approx bounding latlng in radians
  31. return array($latmin, $latmax, $lngmin, $lngmax);
  32. }
  33.  
  34. function distance_between_points_deg($lat1, $lng1, $lat2, $lng2){
  35. // latlng in degrees
  36. // return distance in km
  37. return distance_between_points_rad(
  38. deg2rad($lat1), deg2rad($lng1), deg2rad($lat2), deg2rad($lng2) );
  39. }
  40.  
  41. function get_bounding_box_deg($lat, $lng, $range){
  42. // latlng in degrees, $range in km
  43. get_bounding_box_rad(deg2rad($lat), deg2rad($lng), $range));
  44. }
  45.  
  46. // tests
  47. // distance from berlin (52.5200 N, 13.4050 E) to vienna (48.2082 N, 16.3738 E)
  48. echo "Berlin to Vienna " .
  49. distance_between_points_deg(52.5200, 13.4050, 48.2082, 16.3738) . " km \n";
  50. var_dump(get_bounding_box_deg(52.5200, 13.4050, 0.5));
Success #stdin #stdout #stderr 0.01s 82880KB
stdin
Standard input is empty
stdout
Berlin to Vienna 523.65801909981 km 
array(4) {
  [0]=>
  float(52.52449660803)
  [1]=>
  float(52.51550339197)
  [2]=>
  float(13.397610151427)
  [3]=>
  float(13.412389848573)
}
stderr
PHP Notice:  Use of undefined constant rad2deg - assumed 'rad2deg' in /home/HFPy8v/prog.php on line 43