如何根据纬度和经度计算的距离对数组进行排序。

时间:2016-07-05 05:48:32

标签: ios nsmutablearray

我有一个自定义对象数组。并且对象具有包括纬度和经度的参数。我想根据它们与当前位置的距离对该数组进行排序。 我能够获得当前位置和每个对象之间的距离。但我不知道如何在计算距离后对其进行排序。 对于Eg:

MainArray = [{name:NYC, lat:1.11, lng:2.22}, {name:CAL, lat:3.33, lng:4.44}, {name:LA, lat:5.55, lng:6.66}].

所以,让我们说我在三个地方的中心,然后我想按附近的顺序对它们进行排序。对不起,如果上面的语法错误,因为我不能发布原始数据,因为它太大了。

我怎样才能做到这一点?请帮忙。

2 个答案:

答案 0 :(得分:2)

与之前的答案几乎相同,但没有添加字段:

CLLocation *yourLocation = [[CLLocation alloc] initWithLatitude:.... longitude:...];
NSArray *array = @[@{ @"name": @"NYC", @"lat": @1.11, @"lng": @2.22}, @{@"name":@"CAL", @"lat":@3.33, @"lng":@4.44}, @{@"name":@"LA", @"lat":@5.55, @"lng":@6.66}];
array = [array sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *obj1, NSDictionary *obj2) {
    CLLocation *location1 = [[CLLocation alloc] initWithLatitude:[obj1[@"lat"] double]  longitude:[obj1[@"lng"] double]];
    CLLocation *location2 = [[CLLocation alloc] initWithLatitude:[obj2[@"lat"] double]  longitude:[obj2[@"lng"] double]];

    CLLocationDistance distance1 = [location1 distanceFromLocation:yourLocation];
    CLLocationDistance distance2 = [location2 distanceFromLocation:yourLocation];

    if (distance1 > distance2) {
        return (NSComparisonResult)NSOrderedDescending;
    }

    if (distance1 < obj2 distance2) {
        return (NSComparisonResult)NSOrderedAscending;
    }
    return (NSComparisonResult)NSOrderedSame;
}];

答案 1 :(得分:0)

您可以在名为 distanceFromLocation 的对象中添加另一个字段。

然后在您需要显示距离之前,使用以下代码更新对象数组中的 distanceFromLocation

 CLLocation *arrayCoord = [[CLLocation alloc] initWithLatitude:lat1 longitude:long1];

 CLLocation *yourLocation = [[CLLocation alloc] initWithLatitude:yourLocationLat longitude:yourLocationLong];

 CLLocationDistance distance = [arrayCoord distanceFromLocation:yourLocation];

之后使用排序描述符对对象数组进行排序

NSSortDescriptor *sortDescriptor;
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"distanceFromLocation"
                                              ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray = [arrayOfYourObjects sortedArrayUsingDescriptors:sortDescriptors];
相关问题