Home > Article > Backend Development > PHP calculates the distance of all users within 3 kilometers
/** * 计算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['left-top']['lat'] . " and lng>" . $fourpoint['left-top']['lng'] . " and lng<" . $fourpoint['right-bottom']['lng'] . " {$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.