1

我有一个array包含不同的locations' addresses. 我还检索了用户的当前位置。

在数组中的所有位置中,我想找到nearest. 一种方法可能是比较Lat-Long所有方法,但还有其他方法可以解决吗?

注意:not performing nearby location search要检索地址。假设我已经将它们存储在一个数组中。

4

2 回答 2

4

您可以使用Location来确定两个地址之间的距离:

private static float distance(LatLng current, LatLng last){
    if(last==null)
        return 0;
    Location cL = new Location("");
    cL.setLatitude(current.latitude);
    cL.setLongitude(current.longitude);

    Location lL = new Location("");
    lL.setLatitude(last.latitude);
    lL.setLongitude(last.longitude);

    return lL.distanceTo(cL);
}
于 2013-04-11T13:07:44.820 回答
0

如果您需要真正的最近位置,请使用Location.distanceBetween.

如果您有很多位置并且需要更快地执行代码,我建议使用以下公式:

double diffLat = Math.abs(lat1 - lat2);
double diffLng = Math.abs(lng1 - lng2);
if (diffLng > 180) {
    diffLng = 360 - diffLng;
}
double distanceSquared = diffLat * diffLat + diffLng * diffLng;

不要计算这个的 sqrt,因为这不需要找到(大约)最近的位置。只需比较平方值。

之所以存在,if是因为您可能拥有经度为 -179 和 +179 的位置,并且它们彼此靠近。

根据数据的不同,您也可以尝试对已排序数据进行二分查找的算法,但这里有 2 个维度,因此不像int在 sorted中查找那么简单int[]

于 2013-04-11T13:11:00.817 回答