问题
I want to detect which annotation pin is the closest to the current location of the user. I already added the annotation pins. How would you do this?
回答1:
This is all from memory - but I think this should do the trick:
- (MKPointAnnotation *)cloestAnnotation {
// create variables you'll use to track the smallest distance measured and the
// closest annotation
MKPointAnnotation *closestAnnotation;
CLLocationDistance smallestDistance = 9999999;
// loop through your mapview's annotations (if you're using a different type of annotation,
// just substitude it here)
for (MKPointAnnotation *annotation in _mapView.annotations) {
// create a location object from the coordinates for the annotation so you can easily
// compare the two locations
CLLocation *locationForAnnotation = [[CLLocation alloc] initWithLatitude:annotation.coordinate.latitude longitude:annotation.coordinate.longitude];
// calculate the distance between the user's location and the location you just created
// from the annoatation's coordinates
CLLocationDistance distanceFromUser = [_mapView.userLocation.location distanceFromLocation:locationForAnnotation];
// if this calculated distance is smaller than the currently smallest distance, update the
// smallest distance thus far as well as the closest annotation
if (distanceFromUser < smallestDistance) {
smallestDistance = distanceFromUser;
closestAnnotation = annotation;
}
}
// now you can do whatever you want with the closest annotation
return closestAnnotation;
}
来源:https://stackoverflow.com/questions/25517371/detect-closest-annotation-pin