2015-11-26 41 views
1

我已經回顧了幾個類似於我的問題,但沒有任何運氣。從我所能看到的我需要創造一個可比較的,但沒有任何成功。這是我目前所擁有的。根據當前位置從最近到最遠排序Java列表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; 
}*/ 
+0

是您的問題「我如何編寫比較器?」或「如何正確地獲得兩個地點之間的距離?」? –

+0

@Aron_dc任何可以讓我根據我擁有的距離排序列表的東西。我相信比較是我需要的,但我不確定。 – alphamalle

回答

1

我沒有您的課程或安裝的Android SDK,因此請隨時編輯我的文章。其基本思路是像

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

的基本思想是用你的匿名比較中的當前位置使用計算的距離值來比較列表的對象。

0

問題是你想排序的位置,但距離兩個位置之間的區別。您可以通過這種方式輕鬆排序距離,但不能排序位置(從哪個位置到另一個位置)。你可以嘗試使自己的類,即。路線(位置A,位置B)和列表u應該很容易按距離排序(比較方法中的計數距離),只需調用排序方法就可以收集。

相關問題