如何在python上找到纬度和经度点的最近邻居?

时间:2016-05-19 13:14:18

标签: python geolocation scipy nearest-neighbor kdtree

输入:

swift

输出: point = (lat, long) places = [(lat1, long1), (lat2, long2), ..., (latN, longN)] count = L =靠近neighbors的{​​{1}}的子集。 (places

问题: 我可以使用kd-tree快速查找具有纬度和经度的点的最近邻 s 吗? (例如, scipy 中的实现)

是否有必要转换坐标x,y中点的地理坐标(纬度和经度)?

这是解决这个问题的最佳方法吗?

3 个答案:

答案 0 :(得分:1)

老实说,我不知道使用kd树是否可以正常工作,但我的预感说它会不准确。

我认为您需要使用更大的圆距离来获得准确的距离。

# original formula from  http://www.movable-type.co.uk/scripts/latlong.html 
def distance_haversine(p1, p2):
    """
    Calculate the great circle distance between two points 
    on the earth (specified in decimal degrees)

    Haversine formula: 
        a = sin²(Δφ/2) + cos φ1 ⋅ cos φ2 ⋅ sin²(Δλ/2)
                        _   ____
        c = 2 ⋅ atan2( √a, √(1−a) )
        d = R ⋅ c

    where φ is latitude, λ is longitude, R is earth’s radius (mean radius = 6,371km);
            note that angles need to be in radians to pass to trig functions!

    :p1:     (tup) lat,lon
    :p2:     (tup) lat,lon
    """
    lat1, lon1 = p1
    lat2, lon2 = p2
    for p in [p1, p2]:
        validate_point(p)

    R = 6371.0 # km - earths's radius

    # convert decimal degrees to radians 
    lat1, lon1, lat2, lon2 = map(radians, [lat1, lon1, lat2, lon2])

    # haversine formula 
    dlon = lon2 - lon1
    dlat = lat2 - lat1

    a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
    c = 2 * asin(sqrt(a)) # 2 * atan2(sqrt(a), sqrt(1-a))
    d = R * c
    return d

答案 1 :(得分:1)

认为您正试图解决k Nearest Neighbor问题。

由于您的数据集位于2D中,因此kd-tree可以很好地工作,一般来说,我不知道辛辣。

但是,如果你的积分开始生活在更高的维度,那么kd-tree will not be a smart choice

答案 2 :(得分:0)

scikit-learn提供了一个支持Haversine指标的BallTree类。另请参见this SO question