douchun1948 2017-03-30 17:08
浏览 57
已采纳

高效的计算距离的方法

I am making a dating site with a search function to find matches. One of the criteria is the distance between you and the possible match. How should I calculate the distance? I think calculating the exact distance for all possible matches might be too resource-intensive.I want a different solution so the nearby people are shown without being resource-intensive.

I had this idea:

When someone registers, save their coordinates rounded to (for the latitude) the nearest 5 minutes (=9 km) in the database? When searching for a match, search trough the database looking for the same coordinates as the user. After the matches are found, the exact distance could still be calculated.

How would that work for the longitude? Are there any better ways of doing this? I am not looking for the formula for calculating the distance. How can I find nearby matches without having to calculate the distance to every single possible match (thousands)?

  • 写回答

1条回答 默认 最新

  • dtw52353 2017-03-30 17:16
    关注

    At first you can pick the latitude longitude of two users and can convert them into distance as following functions:

    function distance($lat1, $lon1, $lat2, $lon2, $unit) {
    
      $theta = $lon1 - $lon2;
      $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
      $dist = acos($dist);
      $dist = rad2deg($dist);
      $miles = $dist * 60 * 1.1515;
      $unit = strtoupper($unit);
    
      if ($unit == "K") {
        return ($miles * 1.609344);
      } else if ($unit == "N") {
          return ($miles * 0.8684);
        } else {
            return $miles;
          }
    }
    
    echo distance(32.9697, -96.80322, 29.46786, -98.53506, "M") . " Miles<br>";
    echo distance(32.9697, -96.80322, 29.46786, -98.53506, "K") . " Kilometers<br>";
    echo distance(32.9697, -96.80322, 29.46786, -98.53506, "N") . " Nautical Miles<br>";
    
    ?>
    

    Hope it helps.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度