Haversine distance calculation between two points in Laravel

前端 未结 7 1634
迷失自我
迷失自我 2020-12-13 16:45

I\'m working on a laravel appliciation in which I need to find all the products that are within a certain radius of the user\'s coordinates. Products have a one to many rela

7条回答
  •  情深已故
    2020-12-13 17:01

    Using Haversine method, you can calculate distance between two points using this function. It works but I don't know how to implement this in Laravel. Thought of sharing this anyway.

    $lat1 //latitude of first point
    $lon1 //longitude of first point 
    $lat2 //latitude of second point
    $lon2 //longitude of second point 
    $unit- unit- km or mile
    
    function point2point_distance($lat1, $lon1, $lat2, $lon2, $unit='K') 
        { 
            $theta = $lon1 - $lon2; 
            $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta)); 
            $dist = acos($dist); 
            $dist = rad2deg($dist); 
            $miles = $dist * 60 * 1.1515;
            $unit = strtoupper($unit);
    
            if ($unit == "K") 
            {
                return ($miles * 1.609344); 
            } 
            else if ($unit == "N") 
            {
            return ($miles * 0.8684);
            } 
            else 
            {
            return $miles;
          }
        }   
    

提交回复
热议问题