一尘不染

MySQL大圆距离(Haversine公式)

mysql

我有一个工作的PHP脚本,该脚本获取经度和纬度值,然后将它们输入到MySQL查询中。我只想将其制作成MySQL。这是我当前的PHP代码:

if ($distance != "Any" && $customer_zip != "") { //get the great circle distance

    //get the origin zip code info
    $zip_sql = "SELECT * FROM zip_code WHERE zip_code = '$customer_zip'";
    $result = mysql_query($zip_sql);
    $row = mysql_fetch_array($result);
    $origin_lat = $row['lat'];
    $origin_lon = $row['lon'];

    //get the range
    $lat_range = $distance/69.172;
    $lon_range = abs($distance/(cos($details[0]) * 69.172));
    $min_lat = number_format($origin_lat - $lat_range, "4", ".", "");
    $max_lat = number_format($origin_lat + $lat_range, "4", ".", "");
    $min_lon = number_format($origin_lon - $lon_range, "4", ".", "");
    $max_lon = number_format($origin_lon + $lon_range, "4", ".", "");
    $sql .= "lat BETWEEN '$min_lat' AND '$max_lat' AND lon BETWEEN '$min_lon' AND '$max_lon' AND ";
    }

有谁知道如何完全使用MySQL?我浏览了一下互联网,但是关于它的大多数文献都令人困惑。


阅读 530

收藏
2020-05-17

共1个答案

一尘不染

来自Google Code常见问题解答-使用PHP,MySQL和Google
Maps创建商店定位器

这是一条SQL语句,它将找到距离37,-122坐标25英里范围内的最近20个位置。它根据该行的纬度/经度和目标纬度/经度计算距离,然后仅查询距离值小于25的行,按距离对整个查询进行排序,并将其限制为20个结果。要按公里而不是英里进行搜索,请将3959替换为6371。

SELECT id, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) 
* cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * sin(radians(lat)) ) ) AS distance 
FROM markers 
HAVING distance < 25 
ORDER BY distance 
LIMIT 0 , 20;
2020-05-17