Find the top 5 nearest locations from given location

149 views Asked by At

I am creating an app in which I need top 5 nearest riders location from cook location and then store in list an ascending order. I have found the nearest rider location from cook location. But i am bit confused how to add top 5 in list.

That's my code for finding nearest rider location.

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();
        }
1

There are 1 answers

14
Aznhar On

I think you just have to replace "smallestDistance" by an array of 5 and then just test every cases and you will have the closest one in the first element of the array and the far one ine the fifth element of the array :

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());
}