1

I'm developing an iPhone app with annotations on a map, and I've finished inserting all the annotations. The code I've used for all the annotations (x100) is:

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];

What I'm wondering about is how can I get all these locations in a list that shows the closest annotations to the users location?

4

1 回答 1

3

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

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

@property (nonatomic, assign) CLLocationDistance distance;

和合成到.m 文件ofcourse。其次,当您收到新位置时,在您的 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];
    }];

    [...]
}

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

于 2012-12-28T00:49:51.270 回答