2012-12-27 60 views
1

我正在開發一個帶有註釋的iPhone應用程序,我已經完成了插入所有註釋的工作。我已經用了所有的註釋(X100)的代碼是:MapKit中最接近的註釋列表

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

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

myAnnotation1.coordinate=theCoordinate1; 
[email protected]"Økern Senter - DNB"; 
[email protected]"Økernveien 145, 0580 OSLO"; 

[mapView addAnnotation:myAnnotation1]; 

[annotations addObject:myAnnotation1]; 

我不知道什麼是我怎樣才能在顯示最接近的註釋給用戶位置的列表中的所有這些位置?

回答

3

你需要做的是計算用戶和註釋之間的距離。

首先,在你的MyAnnotation,添加一個變量保持距離值: 添加以下​​:

@property (nonatomic, assign) CLLocationDistance distance; 

和合成到ofcourse .m文件。 其次,在你的MapView類(一個保持註釋ECT)添加以下代碼,當你收到一個新的位置:

- (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 ECT,這是根據排序從最近距離到最遠距離的距離。 當然

+0

謝謝!接受用戶位置的最佳方式是什麼,就像你在第二個代碼中寫的那樣? –

+0

使用[核心位置框架](http://developer.apple.com/library/ios/#documentation/CoreLocation/Reference/CoreLocation_Framework/_index.html)。我爲它添加了委託方法。不過,我建議您選擇計算代碼,因爲委託方法可以經常返回。也許你不想重新計算用戶移動的每一釐米。 –

+0

@GThamanTitan問題解決了嗎? –