あなたがする必要があるのは、ユーザーと注釈の間の距離を計算することです。
まず、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];
}];
[...]
}
これで、tableView ectのソースとして使用できますsortedArray
。これは、最も近い距離から最も長い距離までの距離に従ってソートされます。もちろん