duanliaoyin3171 2012-05-27 00:55
浏览 31
已采纳

PHP排序最近的坐标

I have a MySQL table in a PHP webservice containing longitude and latitude. I want to send the user only the, let's say, 5 closest coordinates. I wrote the method which calculates a distance from coordinates to the ones the user sent in the POST request, but I'm not sure on how to sort it and only send back a few.

Here is the distance method:

function  distance($longToCompare,$latToCompare) {
    $dlong = $request_long - $longToCompare;
    $dlat = $request_lat - $latToCompare;
    $a = pow(sin($dlat/2)) + cos($latToCompare)*cos($request_lat)*pow(sin($dlong/2));
    $c = 2*atan2(sqrt($a),sqrt(1-$a));
    return 6373*$c; 
}

and the user currently gets the whole DB (for now, while developing it's small, but in the future it could be rather big)

$q = mysql_query("SELECT * FROM Coordinates");
$coordinates = array ();
while ($e = mysql_fetch_assoc($q)) {
    $coordinates[] = $e;
}
print (json_encode($coordinates));

Can anyone point me to the right direction? I'm rather new to PHP, I know I can create a custom sorting using uasort, but i'm not quite sure on how to use it using this distance function.

EDIT: Using @Norse 's solution, the current query is:

$request_long = $_POST['longitude'];
$request_lat = $_POST['latitude'];
    $km = 0.5;
        $query = "SELECT *, 
    ( 6373 * acos( cos( radians('$request_lat') ) * 
    cos( radians( latitude ) ) * 
    cos( radians( longitude ) - 
    radians('$request_long') ) + 
    sin( radians('$request_lat') ) * 
    sin( radians( latitude ) ) ) ) 
    AS distance FROM Coordinates HAVING distance < '$km' ORDER BY distance ASC LIMIT 0, 5";
        $coordinates = array ();
        while ($e = mysql_fetch_assoc($query)) {
            $coordinates[] = $e;
        }
        print (json_encode($coordinates));
  • 写回答

3条回答 默认 最新

  • dsbc80836 2012-05-27 01:28
    关注

    Using Google's algorithm:

    $lon = //your longitude
    $lat = //your latitude
    $miles = //your search radius
    
    $query = "SELECT *, 
    ( 3959 * acos( cos( radians('$lat') ) * 
    cos( radians( latitude ) ) * 
    cos( radians( longitude ) - 
    radians('$lon') ) + 
    sin( radians('$lat') ) * 
    sin( radians( latitude ) ) ) ) 
    AS distance FROM yourtable HAVING distance < '$miles' ORDER BY distance ASC LIMIT 0, 5"
    

    latitude and longitude in this query are going to be your lat/lon column names.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 深度学习残差模块模型
  • ¥20 两个不同Subnet的点对点连接
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计
  • ¥23 (标签-bug|关键词-密码错误加密)