根据当前位置 Android 从最近到最远对 Java 中的列表进行排序

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

我已经复习了几个与我类似的问题,但没有运气。据我所知,我需要创建一个可比较的,但没有取得任何成功。这是我目前拥有的。

我能够成功获得 2 个提供我当前位置的双打。一个用于纬度,一个用于经度。

 double myCurrentLong;
 double myCurrentLat;

我需要排序的列表如下。

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

每个 "myLocations" 都包含纬度和经度。需要说明的是,我得到了正确的数字,但是 运行 在尝试对它们进行排序时遇到了问题。

感谢所有帮助。谢谢。

下面是我尝试通过先获取距离来解决问题的尝试。为了测试,我在那里使用虚拟数据。

 /*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;
}*/

问题是你试图对位置进行排序,但按距离排序两个位置之间有什么区别。 通过这种方式,您可以轻松地对距离进行排序,但不能对位置(从什么位置到另一个位置)进行排序。 你可以尝试自己制作 class 即。 Route (Location A, Location B) 和 List u 应该很容易按距离排序(在比较方法中计算距离),只需在集合上调用排序方法即可。

我没有你的 类 或安装的 Android SDK,所以请随意编辑我的 post。基本思路是这样的

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

基本思想是使用您在匿名比较器中的当前位置,使用您计算出的距离值来比较列表中的对象。