PHP查询距离较近的数据

已知:

用户经纬度:$lat,$lon

数据库经纬度字段:d_lat,d_lon

 

工具函数

//注意替换数据库经纬度字段值
//入参为用户经纬度,as_name为距离字段别名
public function get_distance_sql($lat, $lng, $as_name = 'distance') { return sprintf('round(6371*sqrt( pow((PI()*(abs(`d_lat`-%f))/180) * cos(PI()*(`d_lat`+%f)/360),2) + pow((PI()*abs(`d_lon`-%f)/180),2)),4) as %s', $lat, $lat, $lng, $as_name); }

 

查询函数

$sql  = "SELECT id,d_lat,d_lon," . $this->get_distance_sql($latitude, $longitude) . " FROM table_name ORDER BY distance ASC";
$List = Db::query($sql);

 

posted @ 2021-12-28 17:31  悬剑丶  阅读(229)  评论(0编辑  收藏  举报