检测最近的注释引脚

时间:2014-08-27 01:02:22

标签: objective-c mapkit

我想检测哪个注释引脚最接近用户的当前位置。我已经添加了注释引脚。 你会怎么做?

1 个答案:

答案 0 :(得分:0)

这完全来自记忆 - 但我认为这应该可以解决问题:

- (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;
}
相关问题