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

oknrviil  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(430)

我有一张表,上面有id、纬度(lat)、经度(lng)、高度(alt)。我有一些坐标,我想在数据库中找到最近的条目。我使用了这个,但还不能正常工作:

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

我有一张表,上面有6个最近的点,显示了纬度、经度和海拔高度。

t3psigkw

t3psigkw1#

查询以获取中的最近距离 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)
z5btuh9x

z5btuh9x2#

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

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改变为每次比较的平均高度,但在距离较大的情况下,这可能会产生误导,如前面所讨论的。

相关问题