【问题标题】:Find the top 5 nearest locations from given location查找距给定位置最近的 5 个位置
【发布时间】:2018-08-13 05:12:18
【问题描述】:

我正在创建一个应用程序,其中我需要距离厨师位置最近的 5 个骑手位置,然后按升序存储在列表中。我找到了离厨师位置最近的骑手位置。但我有点困惑如何在列表中添加前 5 名。

这是我查找最近骑手位置的代码。

try {
            for(Location rlocation : rLocations){
                float distance=  cookerLOCATION.distanceTo(rlocation);
                //int distance = Location.distanceBetween(cookLAT,cookLONG,rlocation.getLatitude(),rlocation.getLongitude(),results);
                if(smallestDistance == -1 || distance < smallestDistance){
                    colsestRiderLocation = rlocation;
                    smallestDistance = distance;
                    comparingValues();
                    Log.d("Closet Rider Location",colsestRiderLocation.toString());
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

【问题讨论】:

    标签: android list google-maps sorting location-based-service


    【解决方案1】:

    我认为您只需将“smallestDistance”替换为 5 的数组,然后只需测试每个案例,您将在数组的第一个元素中拥有最接近的一个,而在数组的第五个元素中拥有最远的一个:

    if(smallestDistance[0] == -1 || distance < smallestDistance[0]){
        colsestRiderLocation = rlocation;
        smallestDistance[0] = distance;
        comparingValues();
        Log.d("Closet Rider Location",colsestRiderLocation.toString());
                }
    else if(smallestDistance[1] == -1 || distance < smallestDistance[1]){
        colsestRiderLocation = rlocation;
        smallestDistance[1] = distance;
        Log.d("Second closet Rider Location",colsestRiderLocation.toString());
    }
    else if(smallestDistance[2] == -1 || distance < smallestDistance[2]){
        colsestRiderLocation = rlocation;
        smallestDistance[2] = distance;
        Log.d("Third closet Rider Location",colsestRiderLocation.toString());
    }
    else if(smallestDistance[3] == -1 || distance < smallestDistance[3]){
        colsestRiderLocation = rlocation;
        smallestDistance[3] = distance;
        Log.d("Fourth closet Rider Location",colsestRiderLocation.toString());
    }
    else if(smallestDistance[4] == -1 || distance < smallestDistance[4]){
        colsestRiderLocation = rlocation;
        smallestDistance[4] = distance;
        Log.d("Fifth closet Rider Location",colsestRiderLocation.toString());
    }
    

    【讨论】:

    • 我认为这将存储相同的位置。喜欢排名第一的最近骑手。
    • 我不认为,因为最近的永远不会进入“else”语句。它将在第一次 if 中输入一次,并且不会在另一次被调用,因此它不会在另一个“else”中输入
    • 我可以使用 ArrayList 而不是数组吗?因为我必须创建动态结构。
    • 是的,我认为这应该以同样的方式工作,我没有尝试过
    • 我在给数组赋值-1时发现了一个问题。它在索引 0 上设置值。它给了我异常 ArrayIndexOutOfBoundsException。我认为 ArrayList 的错误是相同的。 @Aznhar
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-13
    • 1970-01-01
    • 1970-01-01
    • 2021-07-06
    • 2011-04-24
    • 1970-01-01
    相关资源
    最近更新 更多