次の SQL クエリは、球面余弦法則を使用して、テーブル内の座標と座標の間の距離を計算します。
d = acos( sin(φ1).sin(φ2) + cos(φ1).cos(φ2).cos(Δλ) ).R
クエリはSQL 数学関数を使用します
"SELECT Id,Lat,Long,(6367 * acos( cos( radians(center_lat) )
* cos( radians( Lat ) ) * cos( radians( Long ) - radians(center_lng) )
+ sin( radians(center_lat) ) * sin( radians( Lat ) ) ) ) AS distance FROM table
HAVING distance < radius ORDER BY distance ASC LIMIT 0 , 20"
非推奨の関数の代わりにPDOを使用してみてくださいmysql_
// Prepare statement
$stmt = $dbh->prepare("SELECT name, lat, lng, (6367 * acos( cos( radians(?) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(?) ) + sin( radians(?) ) * sin( radians( lat ) ) ) ) AS distance FROM gbarea HAVING distance < ? ORDER BY distance ASC LIMIT 0 , 20");
// Assign parameters
$stmt->bindParam(1,$center_lat);
$stmt->bindParam(2,$center_lng);
$stmt->bindParam(3,$center_lat);
$stmt->bindParam(4,$radius);
//Execute query
$stmt->setFetchMode(PDO::FETCH_ASSOC);
while($row = $stmt->fetch()) {
echo "Name : ".$row['name'].", ";
echo "Lat : ".$row['lat'].", " ;
echo "Lng : ".$row['lng'].", ";
echo "Distance : ".$row['distance'];
echo "<br>";
}