现在很多项目都会用到通过获取用户地理信息计算最近的商家,最近也在折腾这方面,先上代码:

    /**
    *  @desc 根据两点间的经纬度计算距离
    *  @param float $lat 纬度值
    *  @param float $lng 经度值
    */
     static function getDistance($lat1, $lng1, $lat2, $lng2)
     {
         $earthRadius = 6367000; //approximate radius of earth in meters

         /*
           Convert these degrees to radians
           to work with the formula
         */

         $lat1 = ($lat1 * pi() ) / 180;
         $lng1 = ($lng1 * pi() ) / 180;

         $lat2 = ($lat2 * pi() ) / 180;
         $lng2 = ($lng2 * pi() ) / 180;

         /*
           Using the
           Haversine formula

           http://en.wikipedia.org/wiki/Haversine_formula

           calculate the distance
         */

         $calcLongitude = $lng2 - $lng1;
         $calcLatitude = $lat2 - $lat1;
         $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);  $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
         $calculatedDistance = $earthRadius * $stepTwo;

         return round($calculatedDistance) / 1000;   //除以1000 得到的结果就是公里
     }

得到距离后,我们再对这个数组进行排序。

/**
     * [suiSort 数组排序]
     * @param  [type] $data [源数据]
     * @return [type]       [description]
     */
    static function suiSort ($data)
    {
        $sort = array(  
            'direction' => 'SORT_ASC', //排序顺序标志 SORT_DESC 降序;SORT_ASC 升序  
            'field'     => 'juli',       //排序字段  
        ); 

        $arrSort = array();  
        foreach($data AS $uniqid => $row){  
            foreach($row AS $key=>$value){  
                $arrSort[$key][$uniqid] = $value;  
            }  
        }  

        if($sort['direction']){  
            array_multisort($arrSort[$sort['field']], constant($sort['direction']), $data);  
        }  
        return $data;
    }