The userLocation
is static, so don't recreate it each time in your loop. You can also get the location directly with:
CLLocation *userLocation = self.mapView.userLocation.location;
Then, you could do something like, store your distance numbers and annotations into a dictionary, with the distances as keys and the annotations as the values. Once the dictionary is built, sort the allKeys
array and then you can get the annotations associated with the first 3 keys.
Assuming that you always have at least one annotation when you run this:
CLLocation *userLocation = self.mapView.userLocation.location;
NSMutableDictionary *distances = [NSMutableDictionary dictionary];
for (Annotation *obj in annotations) {
CLLocation *loc = [[CLLocation alloc] initWithLatitude:obj.coordinate.latitude longitude:obj.coordinate.longitude];
CLLocationDistance distance = [loc distanceFromLocation:userLocation];
NSLog(@"Distance from Annotations - %f", distance);
[distances setObject:obj forKey:@( distance )];
}
NSArray *sortedKeys = [[distances allKeys] sortedArrayUsingSelector:@selector(compare:)];
NSArray *closestKeys = [sortedKeys subarrayWithRange:NSMakeRange(0, MIN(3, sortedKeys.count))];
NSArray *closestAnnotations = [distances objectsForKeys:closestKeys notFoundMarker:[NSNull null]];