查询最近距离的人

    //找附近的人
    public function nearby(){
        $str = file_get_contents("php://input");
        $str1 = json_decode($str,true);
        $uid = $this->checklogin($str1['username'],$str1['password']);
        if($uid == false){
            $return['status'] = '0';
            $return['rs'] = '未登录';
            echo json_encode($return);exit;
        }
        $nearby = M('nearby');
        $isuser = $nearby->where('uid = '.$uid)->find();
        if(!$isuser){
            $data['uid'] = $str1['uid'];
            $data['longitude'] =  $str1['longitude'];
            $data['latitude'] =  $str1['latitude'];
            $data['username'] =  $str1['username'];
            $data['photo'] =  $str1['photo'];
            $data['ctime'] = time();
            $nearby->add($data);
        }
        
        $row = $nearby->where('uid = '.$uid)->find();//查询本人信息坐标
        if(!empty($row['latitude']) and !empty($row['longitude']))
        {
            $re0 = $nearby->where('uid != '.$uid)->select();//查询其他人的信息
            foreach($re0 as $row0)
            {
                $distance = $this->getDistanceBetweenPointsNew($row['latitude'], $row['longitude'], $row0['latitude'], $row0['longitude']);
                $row0['meter']=$distance['meters'];
                $arr[]=$row0;
            }
            
            $arr= $this->array_sort($arr,'meter');
            $arr = array_slice($arr,0,50); 
            echo json_encode($arr);exit;
            
        }

    }
    

 

    // 比较两个地点的距离
    function getDistanceBetweenPointsNew($latitude1, $longitude1, $latitude2, $longitude2)
    {
        $theta = $longitude1 - $longitude2;
        $miles = (sin(deg2rad($latitude1)) * sin(deg2rad($latitude2))) + (cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * cos(deg2rad($theta)));
        $miles = acos($miles);
        $miles = rad2deg($miles);
        $miles = $miles * 60 * 1.1515;
        $feet = $miles * 5280;
        $yards = $feet / 3;
        $kilometers = $miles * 1.609344;
        $meters = $kilometers * 1000;
        return compact('miles', 'feet', 'yards', 'kilometers', 'meters');
    } 
  // 二维数组按某个key排序
  function array_sort($arr,$keys,$type='desc')
  { 
    $keysvalue = $new_array = array();
    foreach ($arr as $k=>$v){
      $keysvalue[$k] = $v[$keys];
    }
    if($type == 'asc'){
      asort($keysvalue);
    }else{
      arsort($keysvalue);
    }
    reset($keysvalue);
    foreach ($keysvalue as $k=>$v){
      $new_array[$k] = $arr[$k];
    }
    return $new_array; 
  }

 

 

posted @ 2015-05-05 16:38  浮夸浮华  阅读(191)  评论(0编辑  收藏  举报