Detect closest annotation pin

試著忘記壹切 提交于 2020-01-25 15:24:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!