代码之家  ›  专栏  ›  技术社区  ›  standup75

确定一个范围内的经度和纬度

  •  1
  • standup75  · 技术社区  · 15 年前

    我的数据库中有位置。位置具有纬度和经度属性(取自谷歌地图,示例:48.809591)。 是否有任何查询可以帮助我检索其他位置范围内的位置?

    例子: 我的位置A的纬度为48.809591,经度为2.124009,我想检索数据库中距离位置A 5英里以内的所有位置对象。

    我的第一个想法是在一个正方形中检索位置,其中location.Latitude<A.Latitude+5 miles和location.Latitude>A.Latitude-5 miles和location.Latitude<A.Latitude+5 miles和location.Latitude>A.Latitude-5 miles,然后借助某种工具从返回的数组中删除不相关的位置。喜欢 http://www.movable-type.co.uk/scripts/latlong.html

    有什么想法吗?

    3 回复  |  直到 12 年前
        1
  •  2
  •   Daniel Vassallo    15 年前

    以防使用MySQL作为DBMS ,您可能有兴趣查看以下演示文稿:

    作者描述了如何使用 Haversine Formula 在MySQL中,通过接近来排序空间数据,并将结果限制在一个定义的半径内。更重要的是,他还描述了如何避免使用纬度和经度列上的传统索引对此类查询进行全表扫描。


    即使你没有,这仍然是有趣和适用的。
    还有一个 pdf version 演示文稿。

        2
  •  0
  •   Randy    15 年前

    我想,你想要的计算方法叫做大圆距离:

    http://en.wikipedia.org/wiki/Great-circle_distance

        3
  •  0
  •   Peter Mortensen Pieter Jan Bonestroo    15 年前

    你需要一个距离函数。

    为了 SQL Server 它看起来像这样(注意距离是以公里为单位的)。

        CREATE FUNCTION distance
        (
          @startLatitude float, 
          @startLongitude float, 
          @endLatitude float,
          @endLongitude float
        )
        RETURNS float
        AS
        BEGIN
    
          DECLARE @distance float;
    
          set @distance = 
            6371 * 2 * atn2(sqrt(power(sin(pi() / 180 * (@endLatitude - @startLatitude) / 2), 2) +
            power(cos(@startLatitude * pi() / 180), 2) *
            power(sin(pi() / 180 * (@endLongitude - @startLongitude) / 2), 2)),
            sqrt(1 - power(sin(pi() / 180 * (@endLatitude - @startLatitude) / 2), 2) +
            power(cos(@startLatitude * pi() / 180), 2) *
            power(sin(pi() / 180 * (@endLongitude - @startLongitude) / 2), 2)));
          RETURN @distance
        END