检测最接近的注释图钉 [英] Detect closest annotation pin
本文介绍了检测最接近的注释图钉的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想检测哪个注释图钉最接近用户的当前位置.我已经添加了注释图钉. 你会怎么做?
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?
推荐答案
这全部来自内存-但我认为这应该可以解决问题:
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;
}
这篇关于检测最接近的注释图钉的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文