Objective c 检测最近的注释pin

Objective c 检测最近的注释pin,objective-c,mapkit,Objective C,Mapkit,我想检测哪个注释pin最接近用户的当前位置。我已经添加了注释引脚。 你将如何做到这一点?这一切都来自记忆——但我认为这应该可以做到: - (MKPointAnnotation *)cloestAnnotation { // create variables you'll use to track the smallest distance measured and the // closest annotation MKPointAnnotation *closestAn

我想检测哪个注释pin最接近用户的当前位置。我已经添加了注释引脚。
你将如何做到这一点?

这一切都来自记忆——但我认为这应该可以做到:

- (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;
}
-(MKPointAnnotation*)cloestAnnotation{
//创建用于跟踪测量的最小距离和
//最近注释
MKPointAnnotation*closestAnnotation;
CLLocationDistance smallestDistance=9999999;
//循环浏览mapview的注释(如果使用不同类型的注释,
//只需在此处替换即可)
用于(MKPointAnnotation*在_mapView.annotations中的注释){
//根据注释的坐标创建位置对象,以便
//比较这两个位置
CLLocation*locationForAnnotation=[[CLLocation alloc]initWithLatitude:annotation.coordinate.latitude-longitude:annotation.coordinate.longitude];
//计算用户位置与刚创建的位置之间的距离
//从注释的坐标
CLLocationDistanceFromUser=[\u mapView.userLocation.location distanceFromLocation:locationForAnnotation];
//如果此计算距离小于当前最小距离,请更新
//迄今为止的最小距离以及最近的注释
if(距离用户<最小距离){
smallestDistance=与用户的距离;
closestAnnotation=注释;
}
}
//现在,您可以使用最接近的注释执行任何操作
返回符号;
}

太好了,这有意义吗?差不多-就像我说的,我是新手,但我知道发生了什么。酷,如果你有任何问题,请告诉我。