2

我有一个定义了两个属性的核心数据模型

  • (双)纬度
  • (双)经度

现在,我想获取这些对象并根据它们与用户当前位置的比较距离对它们进行排序。我已经知道如何获取当前位置,但我仍然不知道如何根据两个属性对结果进行排序。

我已经搜索过类似的东西,但我仍然有点困惑。

如果有人能指出我正确的方向,那就太好了。

谢谢

4

3 回答 3

3

使用比较器块进行排序非常容易

NSArray *positions = //all fetched positions
CLLocation *currentLocation   = // You said that you know how to get this.


positions = [positions sortedArrayUsingComparator: ^(id a, id b) {
    CLLocation *locationA    = [CLLocation initWithLatitude:a.latitude longitude:a.longitude];
    CLLocation *locationB    = [CLLocation initWithLatitude:b.latitude longitude:b.longitude];
    CLLocationDistance dist_a= [locationA distanceFromLocation: currentLocation];
    CLLocationDistance dist_b= [locationB distanceFromLocation: currentLocation];
    if ( dist_a < dist_b ) {
        return (NSComparisonResult)NSOrderedAscending;
    } else if ( dist_a > dist_b) {
        return (NSComparisonResult)NSOrderedDescending;
    } else {
        return (NSComparisonResult)NSOrderedSame;
    }
}

正如我刚刚从 lnafziger 那里了解到的,您应该在此添加有用的 hack/workaround¹,他正在展示。


¹从这个词中选择对你来说最积极的词

于 2012-05-27T20:29:36.777 回答
2

您可能希望将长/纬度对转换为点之间的地理距离,然后对该单个属性进行排序。

这是一篇关于一些转换方法的文章,具体取决于您想要接受的近似值:http ://en.wikipedia.org/wiki/Geographical_distance

于 2012-05-27T19:47:54.800 回答
2

好吧,你不能。

无论如何,不​​仅仅是通过自行排序纬度/经度。:)

您将需要一个包含与您当前位置的距离的属性。您可以通过添加一个根据需要计算的瞬态属性或创建另一个具有距离的数组来做到这一点(可能更容易)。

要计算您与当前位置的距离,请使用以下方法:

CLLocation *currentLocation   = // You said that you know how to get this.
CLLocation *storedLocation    = [CLLocation initWithLatitude:object.latitude 
                                                   longitude:object.longitude];
/*
 * Calculate distance in meters
 * Note that there is a bug in distanceFromLocation and it gives different
 * values depending on whether you are going TO or FROM a location. 
 * The correct distance is the average of the two:
 */
CLLocationDistance *distance1 = [currentLocation distanceFromLocation:storedLocation];
CLLocationDistance *distance2 = [storedLocation distanceFromLocation:currentLocation];
CLLocationDistance *distance  = distance1 / 2 + distance2 / 2;
于 2012-05-27T19:54:00.760 回答