數據表
其中long,lat
分別爲經度和緯度:
實現代碼
模型中的方法:
public function get_all_byid($id,$page,$row,$long,$lat){
$data = $this->where("fid",$id)
->field("id,name,image,address,`long`,lat,".$this->byLonLat($long,$lat))
->order("distance")
->page($page,$row)
->select();
return $data;
}
計算距離的方法:
lng
:經度
lat
:緯度
public function byLonLat($lng,$lat) {
return <<<EOT
6378.138 * 2 * ASIN(
SQRT(
POW(
SIN(
(
{$lat} * PI() / 180 - lat * PI() / 180
) / 2
),
2
) + COS({$lat} * PI() / 180) * COS(lat * PI() / 180) * POW(
SIN(
(
{$lng} * PI() / 180 - `long` * PI() / 180
) / 2
),
2
)
)
) * 1000
AS distance
EOT;
}
返回結果
distance
:兩個經緯度之間的距離(單位米)
採坑小結
long
屬於mysql中關鍵字,一定要使用反單引號來進行轉義。