簡體   English   中英

Twitter Fabric API:根據位置對推文進行排序(最近的優先)

[英]Twitter fabric API: Sorting tweets based on location (nearest first)

因此,我正在使用Fabric API開發失物招領的應用程序。 它具有一個選項,可以根據用戶的當前位置對收集的推文進行排序。 我發現以下在線方式可以使用比較器進行排序。 但是,這似乎不起作用,並且排序前和排序后的結果完全相同。

public class SortLocations implements Comparator<Tweet> {
    Double currLat;
    Double currLng;

    public SortLocations(Double currLat1, Double currLng1) {
        currLat = currLat1;
        currLng = currLng1;
    }

    @Override
    public int compare(final Tweet tweet1, final Tweet tweet2) {
        double lat1 = 0, lon1 = 0, lat2 = 0, lon2 = 0, distanceToPlace1 = 0, distanceToPlace2 = 0;
        try {
            lat1 = tweet1.coordinates.getLatitude();
            lon1 = tweet1.coordinates.getLongitude();

            lat2 = tweet2.coordinates.getLatitude();
            lon2 = tweet2.coordinates.getLongitude();

            distanceToPlace1 = distance(currLat, currLng, lat1, lon1);
            distanceToPlace2 = distance(currLat, currLng, lat2, lon2);
        } catch (Exception E) {
            Log.d("No coordinates", "");
        }
        return (int) (distanceToPlace1 - distanceToPlace2);
    }

    public double distance(double fromLat, double fromLon, double toLat, double toLon) {
        double radius = 6378137;   // approximate Earth radius, *in meters*
        double deltaLat = toLat - fromLat;
        double deltaLon = toLon - fromLon;
        double angle = 2 * Math.asin(Math.sqrt(
                Math.pow(Math.sin(deltaLat / 2), 2) +
                        Math.cos(fromLat) * Math.cos(toLat) *
                                Math.pow(Math.sin(deltaLon / 2), 2)));
        return radius * angle;
    }
}

這是我的活動中如何使用該類的方法

Collections.sort(tweetsSortedByLocation, new SortLocations(currLat, currLng)); 

其中tweetsSortedByLocation為List類型。 任何幫助都非常感激:)

我可能會建議一種稍微不同的方法,這將使您的生活更輕松,同時又不浪費任何計算時間。

您當前的解決方案可能是n + n log(n)時間:n用於將Tweets添加到集合中,然后n log(n)用於排序。 如果您使用PriorityQueue(在Java中實現為min-heap)而不是常規List(我假設tweetsSortedByLocation是),則它將在添加時進行排序,從而為您提供n log(n)時間:每個n元素和每個插入的log(n)(請考慮二進制搜索)。

您可以像這樣使用PriorityQueue( https://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html ):

PriorityQueue<Tweet> tweetsSortedByLocation = new PriorityQueue<>(10, new SortLocations(currLat, currLong));
tweetsSortedByLocation.add(new Tweet());    // Or however you add them now

您也可以內聯比較器,但是使用SortLocations更好。

現在,為什么排序時什么都沒有改變,這意味着compare()每次必須返回0。 如果您計算的兩個距離之間的差小於1,則會發生這種情況。請看這條線上的整數:

return (int) (distanceToPlace1 - distanceToPlace2);

如果distanceToPlace1和distanceToPlace2之差不超過1,則該整數強制轉換將其變為0,在必須實現比較的方式中,這意味着相等。 (請參閱https://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html 。)因此,請嘗試以下方法(首先將最小距離排序(即,按距離對asc排序)):

if (distanceToPlace1 < distanceToPlace2) {
    return -1;
} else if (distanceToPlace1 > distanceToPlace2) {
    return 1;
} else {
    return 0;
}

我希望能解決您的問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM