mysql - 查询 MySQL 以获取给定英里半径内的纬度和经度坐标

标签 mysql sql geolocation haversine

我目前有一个结构如下的 MySQL 表:

id         name     lon            lat  
-----      -----    -----------    -----------
1          Mark     -76.316528     40.036027
2          John     -95.995102     41.25716
3          Paul     -82.337036     29.645095
4          Dave     -82.337036     29.645095
5          Chris    -76.316528     40.036027

我目前查询数据库以查看用户位置是否在给定位置的特定英里半径内的方法是这样做的。

function Haversine($lat_from, $lon_from, $lat_to, $lon_to) {
    $radius = 6371000;
    $delta_lat = deg2rad($lat_to-$lat_from);
    $delta_lon = deg2rad($lon_to-$lon_from);

    $a = sin($delta_lat/2) * sin($delta_lat/2) +
        cos(deg2rad($lat_from)) * cos(deg2rad($lat_to)) *
        sin($delta_lon/2) * sin($delta_lon/2);
    $c = 2*atan2(sqrt($a), sqrt(1-$a));

    // Convert the distance from meters to miles
    return ceil(($radius*$c)*0.000621371);
}

// Set the given location to NYC
$my_lon = -73.9844;
$my_lat = 40.7590;

// Query the DB for all of the users
$sql = "SELECT * FROM users";
$result = mysqli_query($con, $sql)or die(mysqli_error($con));
$count = mysqli_num_rows($result);
$i = 0;

while($row = mysqli_fetch_assoc($result)) {
    $lon[$i] = $row['lon'];
    $lat[$i] = $row['lat'];

    $i++;
}

for($i=0;$i<$count;$i++) {
    // Calculate the distance between each user's location and my location
    $distance = Haversine($my_lat, $my_lon, $lat[$i], $lon[$i);

    if($distance < 50) {
        echo "Close enough";
    }
}

这适用于表格中只有几百行的情况。但是,现在我有几万行,检查这么多行被证明是非常耗时的。我想知道是否有办法使用 Haversine公式只查询 50 英里半径内的行。

最佳答案

余弦公式的球面定律
(37和-122是你半径中心的经纬度)

SELECT id, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) 
    * cos( radians( long ) - radians(-122) ) + sin( radians(37) ) * sin(radians(lat)) ) ) AS distance 
FROM myTable
HAVING distance < 50
ORDER BY distance 

特点

  • 最快
  • 精度类似于 Harvesine 公式

Haversine 公式

SELECT id, 3959 * 2 * ASIN(SQRT(POWER(SIN((37 - abs(lat)) * pi()/180 / 2), 2)
       + COS(37 * pi()/180 ) * COS(abs(lat) * pi()/180)
       * POWER(SIN((-122 - long) * pi()/180 / 2), 2) )) as  distance
FROM myTable
HAVING distance < 50
ORDER BY distance

特点

  • 对浮点错误更稳健

请注意,3959 是以英里为单位的地球半径。以千米(km)为单位的地球半径:6371

您可以找到更多信息here

关于mysql - 查询 MySQL 以获取给定英里半径内的纬度和经度坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29553895/

相关文章:

Python包: Get the country based on adress(non-ip)

mysql - Union在mysql中与group by一起使用时不起作用?怎么了?

mysql - 使用 ActiveRecord 在遗留数据库中按日期对日期时间列进行分组

sql - 如何选择所有具有以特定数字开头的 bigint 字段的记录?

sql - 每个距离与最大值的距离

iphone - 从坐标中获取位置名称?

mysql - MYSQL合并两列

php - 从 Ajax/PHP 调用 MySQL SP 返回空值

sql - BigQuery 选择 * 两列除外

java - 如何将地理位置点数据反序列化为Java实体?