PHP – Pro9ramming https://pro9ramming.com Software craftsman's blog Wed, 15 Apr 2020 17:51:05 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.3 Distance between two geographical points in PHP https://pro9ramming.com/distance-between-two-geographical-points-in-php/ Sat, 21 Feb 2015 21:43:27 +0000 http://pro9ramming.com/blog/?p=253 Continue reading Distance between two geographical points in PHP]]> This function returns distance in km or miles between two geographical points. Because of the near-spherical shape of the Earth (technically an oblate spheroid), calculating an accurate distance between two points requires the use of spherical geometry and trigonometric math functions. However, you can calculate an approximate distance using much simpler math functions (for example with Euclidean distance). For many applications the approximate distance calculation provides sufficient accuracy with much less complexity. The following approximate distance calculations are relatively simple, but can produce distance errors of 10 percent or more. These approximate calculations are performed using latitude and longitude values in degrees.
But this is only for purposes of fast PHP calculation so here is the code:

<?php
function getDistance($a_lat,$a_lng,$b_lat,$b_lng,$mi=false){
    var $radius;
    ($mi ? $radius=10253 : $radius=6371);
    $a_lat = deg2rad($a_lat);
    $a_lng = deg2rad($a_lng);
    $b_lat = deg2rad($b_lat);
    $b_lng = deg2rad($b_lng);
    if($a_lat==$b_lat && $a_lng==$b_lng) return 0;
    if ((sin($b_lat)*sin($a_lat ) + cos($b_lat)*cos($a_lat )*cos($b_lng-$a_lng))>1)
        return $radius * acos(1));
     return $radius * acos(sin($b_lat)*sin($a_lat)+cos($b_lat)*cos($a_lat)*cos($b_lng-$a_lng)));
}
?>

 

 

]]>