开发者

Get 5 Nearest Annotations MKMapKit

开发者 https://www.devze.com 2023-02-15 04:41 出处:网络
I am using MKMapKit to get the nearest locations in a 100km radius. However I would like to know how I can sort the array into giving me the nearest five annotati开发者_如何转开发ons at the top of the

I am using MKMapKit to get the nearest locations in a 100km radius. However I would like to know how I can sort the array into giving me the nearest five annotati开发者_如何转开发ons at the top of the array.

My current code is:

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


Write your own compare method for annotations:

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

Then you can sort using a selector:

NSArray *sortedArray = [storesLessThan100KAway sortedArrayUsingSelector:@selector(compare:)];


If you're using iOS4, you can use blocks to make this even easier:

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];
0

精彩评论

暂无评论...
验证码 换一张
取 消