我有经纬度,我想从数据库中提取记录,它有最近的经纬度,如果这个距离比指定的长,就不检索它。

表结构:

id
latitude
longitude
place name
city
country
state
zip
sealevel

当前回答

根据文章Geo-Distance-Search-with-MySQL检查以下代码:

例如:找到半径10英里内离我目前位置最近的10家酒店。

#Please notice that (lat,lng) values mustn't be negatives to perform all calculations

set @my_lat=34.6087674878572; 
set @my_lng=58.3783670308302;
set @dist=10; #10 miles radius

SELECT dest.id, dest.lat, dest.lng,  3956 * 2 * ASIN(SQRT(POWER(SIN((@my_lat -abs(dest.lat)) * pi()/180 / 2),2) + COS(@my_lat * pi()/180 ) * COS(abs(dest.lat) *  pi()/180) * POWER(SIN((@my_lng - abs(dest.lng)) *  pi()/180 / 2), 2))
) as distance
FROM hotel as dest
having distance < @dist
ORDER BY distance limit 10;

#Also notice that distance are expressed in terms of radius.

其他回答

在极端情况下,这种方法会失败,但为了性能考虑,我跳过了三角函数,只是简单地计算对角线的平方。

这个问题一点也不难,但是如果你需要优化它,它就会变得更加复杂。

我的意思是,你的数据库中有100个地点还是1亿个?这有很大的不同。

如果位置的数量很小,只需执行->,就可以将它们从SQL中取出并放入代码中

Select * from Location

一旦你把它们转换成代码,用哈弗辛公式计算出每一个纬度/长度与原始值之间的距离,然后排序。

这个问题最初的答案是好的,但是mysql的新版本(mysql 5.7.6上)支持地理查询,所以你现在可以使用内置的功能,而不是进行复杂的查询。

你现在可以这样做:

select *, ST_Distance_Sphere( point ('input_longitude', 'input_latitude'), 
                              point(longitude, latitude)) * .000621371192 
          as `distance_in_miles` 
  from `TableName`
having `distance_in_miles` <= 'input_max_distance'
 order by `distance_in_miles` asc

结果以米为单位返回。因此,如果你想计算KM,只需使用。001而不是。000621371192(这是英里)。

MySql文档在这里

听起来你应该只使用PostGIS、SpatialLite、SQLServer2008或Oracle Spatial。它们都可以用空间SQL为您回答这个问题。

查找离我最近的用户:

距离(米)

根据文森特提的公式

i有用户表:

+----+-----------------------+---------+--------------+---------------+
| id | email                 | name    | location_lat | location_long |
+----+-----------------------+---------+--------------+---------------+
| 13 | xxxxxx@xxxxxxxxxx.com | Isaac   | 17.2675625   | -97.6802361   |
| 14 | xxxx@xxxxxxx.com.mx   | Monse   | 19.392702    | -99.172596    |
+----+-----------------------+---------+--------------+---------------+

sql:

-- my location:  lat   19.391124   -99.165660
SELECT 
(ATAN(
    SQRT(
        POW(COS(RADIANS(users.location_lat)) * SIN(RADIANS(users.location_long) - RADIANS(-99.165660)), 2) +
        POW(COS(RADIANS(19.391124)) * SIN(RADIANS(users.location_lat)) - 
       SIN(RADIANS(19.391124)) * cos(RADIANS(users.location_lat)) * cos(RADIANS(users.location_long) - RADIANS(-99.165660)), 2)
    )
    ,
    SIN(RADIANS(19.391124)) * 
    SIN(RADIANS(users.location_lat)) + 
    COS(RADIANS(19.391124)) * 
    COS(RADIANS(users.location_lat)) * 
    COS(RADIANS(users.location_long) - RADIANS(-99.165660))
 ) * 6371000) as distance,
users.id
FROM users
ORDER BY distance ASC

地球半径:6371000(单位:米)