Получите 5 ближайших аннотаций MKMapKit - PullRequest
1 голос
/ 08 марта 2011

Я использую MKMapKit, чтобы получить ближайшие местоположения в радиусе 100 км.Однако я хотел бы знать, как я могу отсортировать массив так, чтобы он давал мне ближайшие пять аннотаций в верхней части массива.

Мой текущий код:

    CLLocation *currentlocation = [[CLLocation alloc] initWithLatitude:annotation.coordinate.latitude longitude:annotation.coordinate.longitude];
    annotation.distanceToTarget = [currentlocation distanceFromLocation:usrlocation];
    annotation.title = [dict objectForKey:@"name"];
    annotation.subtitle = [NSString stringWithFormat:@"%@, %@, %@",[dict objectForKey:@"street"],[dict objectForKey:@"county"], [dict objectForKey:@"postcode"]];
    annotation.subtitle = [annotation.subtitle stringByReplacingOccurrencesOfString:@", ," withString:@""];
    if (annotation.distanceToTarget/1000 < 168) {
        abc++;
        NSLog(@"Distances Lower Than 168: %i", abc);
        [storesLessThan100KAway addObject:annotation];
        NSLog(@"Stores Count: %i", [storesLessThan100KAway count]);
    }
    for (int i = 0; i <= 5; i++) {
        //NSLog(@"Stores Count For Loop: %i", [storesLessThan100KAway count]);
        if ([storesLessThan100KAway count] > 5) {
            [mapView addAnnotation:[storesLessThan100KAway objectAtIndex:i]];
        }
    }   

Ответы [ 2 ]

1 голос
/ 08 марта 2011

Напишите свой собственный метод сравнения для аннотаций:

- (NSComparisonResult)compare:(Annotation *)otherAnnotation {
    if (self.distanceToTarget > otherAnnotation.distanceToTarget) {
        return NSOrderedDescending;
    } else if (self.distanceToTarget < otherAnnotation.distanceToTarget) {
        return NSOrderedAscending;
    } else {
        return NSOrderedSame;
    }
}

Затем вы можете сортировать с помощью селектора:

NSArray *sortedArray = [storesLessThan100KAway sortedArrayUsingSelector:@selector(compare:)];
0 голосов
/ 08 марта 2011

Если вы используете iOS4, вы можете использовать блоки, чтобы сделать это еще проще:

NSComparator compareAnnotations = ^(Annotation *obj1, Annotation *obj2) {
    if (obj1.distanceToTarget > obj2.distanceToTarget) {
        return NSOrderedDescending;
    } else if (obj1.distanceToTarget < obj2.distanceToTarget) {
        return NSOrderedAscending;
    } else {
        return NSOrderedSame;
    }
};

NSArray *sortedArray = [storesLessThan100KAway sortedArrayUsingComparator:compareAnnotations];
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...