如何从 mysql 中的数据库中获取最近的坐标?

How to get nearest coordinates from database in mysql?

我有一个 table,带有 id、纬度 (lat)、经度 (lng)、海拔 (alt)。 我有一些坐标,我想在数据库中找到最近的条目。 我用过这个但还没有正常工作:

SELECT lat,ABS(lat - TestCordLat), lng, ABS(lng - TestCordLng), alt AS distance
FROM dhm200
ORDER BY distance
LIMIT 6

我有一个 table,其中 6 个最近的点显示纬度、经度和高度。

您需要使用 Haversine 公式计算距离,同时考虑纬度和经度:

dlon = lon2 - lon1 
 dlat = lat2 - lat1 
 a = (sin(dlat/2))^2 + cos(lat1) * cos(lat2) * (sin(dlon/2))^2 
 c = 2 * atan2( sqrt(a), sqrt(1-a) ) 
 distance = R * c (where R is the radius of the Earth)

但是,海拔高度增加了问题的难度。如果在 A 点和 B 点之间,具有不同的高度,道路包含很多高海拔差异,那么假设两点之间的高度线导数不变可能会产生误导,根本不考虑这一点可能会产生很大的误导。比较中国某点与印度某点之间的距离,中间有喜马拉雅山脉,与太平洋表面两点之间的距离。一种可能性是将 R 更改为每次比较的平均高度,但在距离很远的情况下,这可能会产生误导,如前所述。

查询 kilometer (km) 距离 mysql 的最近距离:

SELECT id, latitude, longitude, SQRT( POW(69.1 * (latitude - 4.66455174) , 2) + POW(69.1 * (-74.07867091 - longitude) * COS(latitude / 57.3) , 2)) AS distance FROM ranks ORDER BY distance ASC;

您可能希望通过 HAVING 语法限制半径。

... AS distance FROM ranks HAVING distance < '150' ORDER BY distance ASC;

示例:

mysql> describe ranks;
+------------+---------------+------+-----+---------+----------------+
| Field      | Type          | Null | Key | Default | Extra          |
+------------+---------------+------+-----+---------+----------------+
| id         | int           | NO   | PRI | NULL    | auto_increment |
| latitude   | decimal(10,8) | YES  | MUL | NULL    |                |
| longitude  | decimal(11,8) | YES  |     | NULL    |                |
+------------+---------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)

mysql> SELECT id, latitude, longitude, SQRT( POW(69.1 * (latitude - 4.66455174) , 2) + POW(69.1 * (-74.07867091 - longitude) * COS(latitude / 57.3) , 2)) AS distance FROM ranks ORDER BY distance ASC;
+----+-------------+--------------+--------------------+
| id | latitude    | longitude    | distance           |
+----+-------------+--------------+--------------------+
|  4 |  4.66455174 | -74.07867091 |                  0 |
| 10 |  4.13510880 | -73.63690401 |  47.59647003096195 |
| 11 |  6.55526689 | -73.13373892 | 145.86590936973073 |
|  5 |  6.24478548 | -75.57050110 | 149.74731096011348 |
|  7 |  7.06125013 | -73.84928550 | 166.35723903407165 |
|  9 |  3.48835279 | -76.51532198 | 186.68173882319724 |
|  8 |  7.88475514 | -72.49432589 | 247.53456848808233 |
|  1 | 60.00001000 | 101.00001000 |  7156.836171031409 |
|  3 | 60.00001000 | 101.00001000 |  7156.836171031409 |
+----+-------------+--------------+--------------------+
9 rows in set (0.00 sec)