简体   繁体   English

使用Google Maps Places API从一系列位置查找离当前位置最近的位置

[英]Find the location nearest to current location from an array of locations using Google Maps Places API

I have an array containing different locations' addresses . 我有一个包含不同locations' addressesarray I have also retrieved the current location of user. 我还检索了用户的当前位置。

Out of all the locations in array, i would like to find the one which is nearest . 在阵列中的所有位置中,我想找到nearest One way could be to compare Lat-Long of all but is there some other way to go about it? 一种方法可能是比较Lat-Long ,但还有其他方法可以解决吗?

Note: I am not performing nearby location search to retrieve the adresses. 注意:not performing nearby location search来检索地址。 Just assume i already have them stored in an array. 假设我已将它们存储在一个数组中。

You can use Location to determine the distance between two addresses: 您可以使用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);
}

If you need the real nearest location, use Location.distanceBetween . 如果您需要最近的位置,请使用Location.distanceBetween

If you have a lot of locations and require code to execute faster, I'd suggest using this formula: 如果您有很多位置并且要求代码执行得更快,我建议使用以下公式:

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

Don't calculate sqrt of this, as this is not needed to find (approximatelly) the closest location. 不要计算这个的sqrt,因为不需要找到(近似)最近的位置。 Just compare squared values. 只需比较平方值。

The if is there because you may have location with -179 and +179 longitude and these are close to each other. if是存在的,因为您可能有-179和+179经度的位置,这些位置彼此接近。

Depending on the data, you may also try algorithms with binary search on sorted data, but there are 2 dimensions here, so it's not as straightforward as finding int in sorted int[] . 根据数据,您也可以尝试对已排序数据进行二进制搜索的算法,但这里有2个维度,因此它不像在有序int[]查找int那样简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM