I have an array of annotations.I am calculating the distance between each annotation from user location.What I want to know is, how can I find lets say 3 nearest annotations from these distances?
Here is how I am calculating distance from user location to annotations.
CLLocation *userLocation = self.mapView.userLocation.location;
for (Annotation *obj in annotations) {
CLLocation *loc = [[CLLocation alloc] initWithLatitude:obj.coordinate.latitude longitude:obj.coordinate.longitude];
// CLLocation *userLocation = [[CLLocation alloc] initWithLatitude:self.mapView.userLocation.coordinate.latitude longitude:self.mapView.userLocation.coordinate.longitude];
CLLocationDistance dist = [loc distanceFromLocation:userLocation];
int distance = dist;
NSLog(@"Distance from Annotations - %i", distance);
}
The
userLocation
is static, so don't recreate it each time in your loop. You can also get the location directly with: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:
you store all distance in an array and sort it and then pick up top there number