dsyak22488 2015-09-13 22:19
浏览 64
已采纳

按计算的距离(未存储在DB中的距离)对MySQL结果进行排序

I have "Places" stored in a database and I am using PHP to access them. What I want to do is to return all Places sorted by distance relative to a certain place.

This place will be dynamic from an Android application, i.e. I want to display all places closest to the user's location.

What would be the best way to do this? Would it be effective/efficient to retrieve ALL places in PHP into an array, calculate the distance for each place, and then sort that array by distance? Or is there an easier/faster way to accomplish what I need?

Thanks!

  • 写回答

2条回答 默认 最新

  • dsfds4551 2015-09-13 22:32
    关注

    You can do it all in SQL, by calculating the distance on the fly. This is a rough approximation of the distance between stored lat/lon fields and supplied $lat/$lon

    $dlat = "(`lat`-$lat)";
    $dlon = "(`lon`-$lon)*".cos($lat*3.1415/180);
    $dist_sql = "$dlat*$dlat+$dlon*$dlon";
    $sql = "IF(`lat` IS NULL,1e20,$dist_sql)";
    

    then use $sql as you would use any other field, e.g.

    SELECT * FROM `table` ORDER BY $sql ASC
    

    This is far from perfect but should get you started at least.

    The cos() comes in because one degree of longitude is less distance as the (absolute) latitude increases.

    To get from $sql to an actual value in km, divide by 90 and multiply by 10000 km. (again: very rough approximation!)

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

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘