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

时间:2018-01-01 22:15:21

标签: mysql distance

我有一张包含id,纬度(纬度),经度(lng),海拔高度(alt)的表格。 我有一些坐标,我想找到DB中最近的条目。 我用过这个但还没有正常工作:

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

我有一张桌子,上面有6个最近点,向我展示了纬度,经度和海拔高度。

2 个答案:

答案 0 :(得分:0)

您需要使用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点之间,不同高度的道路包含很多高海拔差异,那么假设海拔高度线在两点之间的导数不变可能会产生误导,而不考虑这一点可能会产生误导。比较中国的一个点与印度的一个点之间的距离,其中Himalaja介于太平洋表面两点之间的距离。一种可能性是将R变为每次比较的高度平均值,但如果距离较远,这可能会产生误导,如前所述。

答案 1 :(得分:0)

查询以获取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)