【问题标题】:List of closest annotations in MapKitMapKit 中最接近的注释列表
【发布时间】:2012-12-27 21:01:31
【问题描述】:

我正在开发一个在地图上带有注释的 iPhone 应用程序,并且我已经完成了所有注释的插入。我用于所有注释(x100)的代码是:

CLLocationCoordinate2D theCoordinate1;
theCoordinate1.latitude = 59.92855;
theCoordinate1.longitude = 10.80467;

MyAnnotation* myAnnotation1=[[MyAnnotation alloc] init];

myAnnotation1.coordinate=theCoordinate1;
myAnnotation1.title=@"Økern Senter - DNB";
myAnnotation1.subtitle=@"Økernveien 145, 0580 OSLO";

[mapView addAnnotation:myAnnotation1];

[annotations addObject:myAnnotation1];

我想知道的是如何在一个列表中获取所有这些位置,该列表显示最接近用户位置的注释?

【问题讨论】:

    标签: objective-c xcode ios6 mapkit


    【解决方案1】:

    您需要做的是计算用户和注释之间的距离。

    首先,在您的MyAnnotation 中,添加一个变量来保持距离值: 将以下内容添加到MyAnnotation.h

    @property (nonatomic, assign) CLLocationDistance distance;
    

    当然还有合成到 .m 文件。 其次,当您收到新位置时,在您的 mapView 类(保留注释等)中添加以下代码:

    - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
        [...]
        for (MyAnnotation *annotation in self.mapView.annotations) {
            CLLocationCoordinate2D coord = [annotation coordinate];
            CLLocation *anotLocation = [[CLLocation alloc] initWithLatitude:coord.latitude longitude:coord.longitude];
            annotation.distance = [newLocation distanceFromLocation:anotLocation];
        }
    
        NSArray *sortedArray;
        sortedArray = [self.mapView.annotations sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
            NSNumber *first = [NSNumber numberWithDouble:[(MyAnnotation*)a distance]];
            NSNumber *second = [NSNumber numberWithDouble:[(MyAnnotation*)b distance]];
            return [first compare:second];
        }];
    
        [...]
    }
    

    您现在可以使用sortedArray 作为 tableView 等的源,它根据距离从最近到最长的距离进行排序。 当然

    【讨论】:

    • 谢谢!正如您在第二个代码中所写,接收用户位置的最佳方式是什么?
    • 使用core location framework。我为它添加了委托方法。但是,我建议您将计算代码分开,因为委托方法可以经常返回。也许您不想为用户移动的每厘米重新计算。
    • 还没有:/我是 Obj-C 的初学者,如果可以的话,你认为你可以把用户位置的代码发给我吗?感谢您的帮助!
    • 好的,感谢您的帮助!只是最后一个问题,你知道Apple使用大量注释(200-1000)是否会有任何问题?或者只要我将它们组合在一起就可以了吗? :)
    • 我不能说。只有一种方法可以找出答案,对吧?我无法想象他们有问题。
    猜你喜欢
    • 2012-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多