从用户位置ios查找最近的注释? [英] Find nearest annotations from user location ios?

查看:96
本文介绍了从用户位置ios查找最近的注释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个注释数组.我正在计算每个注释与用户位置之间的距离.我想知道的是,如何从这些距离中找出3个最近的注释?

I have an array of annotations.I am calculating the distance between each annotation from user location.What I want to know is, how can I find lets say 3 nearest annotations from these distances?

这是我计算从用户位置到注释的距离的方法.

Here is how I am calculating distance from user location to annotations.

  CLLocation *userLocation = self.mapView.userLocation.location;

  for (Annotation *obj in annotations) {

       CLLocation *loc = [[CLLocation alloc] initWithLatitude:obj.coordinate.latitude longitude:obj.coordinate.longitude];
      //  CLLocation *userLocation = [[CLLocation alloc] initWithLatitude:self.mapView.userLocation.coordinate.latitude longitude:self.mapView.userLocation.coordinate.longitude];
        CLLocationDistance dist = [loc distanceFromLocation:userLocation];
        int distance = dist;
        NSLog(@"Distance from Annotations - %i", distance);


    }

推荐答案

userLocation是静态的,因此不要每次在循环中都重新创建它.您也可以直接通过以下方式获取位置:

The userLocation is static, so don't recreate it each time in your loop. You can also get the location directly with:

CLLocation *userLocation = self.mapView.userLocation.location;

然后,您可以执行类似的操作,将距离数字和注释存储到字典中,其中距离作为键,注释作为值.构建字典后,对allKeys数组进行排序,然后您可以获得与前三个键相关联的注释.

Then, you could do something like, store your distance numbers and annotations into a dictionary, with the distances as keys and the annotations as the values. Once the dictionary is built, sort the allKeys array and then you can get the annotations associated with the first 3 keys.

假设运行此命令时始终至少有一个注释:

Assuming that you always have at least one annotation when you run this:

CLLocation *userLocation = self.mapView.userLocation.location;
NSMutableDictionary *distances = [NSMutableDictionary dictionary];

for (Annotation *obj in annotations) {
    CLLocation *loc = [[CLLocation alloc] initWithLatitude:obj.coordinate.latitude longitude:obj.coordinate.longitude];
    CLLocationDistance distance = [loc distanceFromLocation:userLocation];

    NSLog(@"Distance from Annotations - %f", distance);

    [distances setObject:obj forKey:@( distance )];
}

NSArray *sortedKeys = [[distances allKeys] sortedArrayUsingSelector:@selector(compare:)];
NSArray *closestKeys = [sortedKeys subarrayWithRange:NSMakeRange(0, MIN(3, sortedKeys.count))];

NSArray *closestAnnotations = [distances objectsForKeys:closestKeys notFoundMarker:[NSNull null]];

这篇关于从用户位置ios查找最近的注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆