alphamalle
alphamalle

Reputation: 192

Sorting a List in Java from closest to furthest based of current location Android

I have reviewed a few questions similar to mine, but have not had any luck. From what I can see I need to create a comparable, but haven't had any success. Here is what I have at the moment.

I am able to successfully get 2 doubles that give my current location. One for Latitude, and one for Longitude.

 double myCurrentLong;
 double myCurrentLat;

The list I need to sort is below.

List<Locations> myLocations = locationLibrary.getLocations();

Each of the "myLocations" contain a Latitude, and a Longitude. Just to be clear I am getting the correct numbers, but running into issues when trying to sort them.

All help is appreciated. Thanks.

Below here is an attempt of mine at trying to solve the issue by getting the distance first. I am using dummy data there for the sake of testing.

 /*private double getDistance(){
    Location locationA = new Location("point A");
    locationA.setLatitude(20.45);
    locationA.setLongitude(30.45);
    Location locationB = new Location("point B");
    locationB.setLatitude(GeoCacheLibrary.get(getActivity()).getLatitude());
    locationB.setLongitude(GeoCacheLibrary.get(getActivity()).getLongitude());
    float distance = locationA.distanceTo(locationB);
    return distance;
}*/

Upvotes: 2

Views: 1730

Answers (2)

Aron_dc
Aron_dc

Reputation: 863

I don't have your classes or an installed Android SDK so feel free to edit my post. The basic idea would be something like

double myCurrentLong;
double myCurrentLat;
//Fill those two variables somehow here
Location myCurrentLoc = new Location("My Current");
locationA.setLongitude(myCurrentLong);
myCurrentLoc.setLatitude(myCurrentLat);

List<Locations> myLocations = locationLibrary.getLocations();
Collections.sort(ls, new Comparator<Location>(){
  public int compare(Location l1, Location l2) {
    return l1.distanceTo(myCurrentLoc) - l2.distanceTo(myCurrentLoc);
  }
});

The basic idea is to use your current location within your anonymous Comparator to compare the objects of your list using your calculated distance value.

Upvotes: 2

Tomas Cejka
Tomas Cejka

Reputation: 96

Problem is ur trying to sort Locations, but by distance what is difference between two locations. U can sort easily distances but not Locations (from what location to another location) by this way. U can try make own class ie. Route (Location A, Location B) and List u should easily sort by distance (count distance in compare method) and just call sort method over collection.

Upvotes: -1

Related Questions