Home  >  Article  >  Backend Development  >  PHP calculates the distance of all users within 3 kilometers

PHP calculates the distance of all users within 3 kilometers

WBOY
WBOYOriginal
2016-07-29 09:15:071207browse
/**
     * 计算3公里范围内的用户
     * @param type $lng  string  经度
     * @param type $lat  string  维度
     * @param type $keyword
     * @return type
     */
    public function actionNearUserlist()
    {
        $lng = $_GET['lng'];
        $lat = $_GET['lat'];
        $keyword = $_GET['keyword'] ? $_GET['keyword'] : "";

        $half = 6371;
        $distance = 20; //3公里
        $dlng = 2 * asin(sin($distance / (2 * $half)) / cos(deg2rad($lat)));
        $dlng = rad2deg($dlng);

        $dlat = $distance / $half;
        $dlat = rad2deg($dlat);

        $fourpoint = array(
                'left-top' => array('lat' => $lat + $dlat,'lng' => $lng - $dlng),
                'right-top' => array('lat' => $lat + $dlat,'lng' => $lng + $dlng),
                'left-bottom' => array('lat' => $lat - $dlat,'lng' => $lng - $dlng),
                'right-bottom' => array('lat' => $lat - $dlat,'lng' => $lng + $dlng)
        );
        $where = "";
        if ($keyword) {
            $where = "and a.name like '%" . $keyword . "%'";
        }
        //从数据库中查询此范围内的网点
        $sql = "select uid,mobile,lng,lat  
                from std_student  
                where lat!=0 and lng!=0 and lat>" . $fourpoint['right-bottom']['lat'] . " and lat<" . $fourpoint[&#39;left-top&#39;][&#39;lat&#39;] .
            " and lng>" . $fourpoint['left-top']['lng'] . " and lng<" . $fourpoint[&#39;right-bottom&#39;][&#39;lng&#39;] . " {$where}";
        $res = Yii::app()->db->createCommand($sql)->queryAll();

        //print_r($res);
        $o = new StdStudent();
        $point1 = array('lat' => $lng,'long' => $lat);
        $distanc = array();
        foreach ($res as $k => $v) {
            $distanc = $o->getTwoDistance($point1['lat'],$point1['long'],$v['lng'],$v['lat']);
            $res[$k]['meters'] = $distanc['meters'];
        }
        //print_r($res);
        if ($res) {
            $this-><strong>ajax</strong>Message(0,'附近三公里的用户',$res);
        } else
            $this-><strong>ajax</strong>Message(-1,'附件用户查询失败');
    }
rrree

The above introduces PHP to calculate the distance of all users within 3 kilometers, including the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn