我建議乾脆在viewDidLoad
創建的MapView:
- (void)viewDidLoad
{
[super viewDidLoad];
MKMapView * map = [[MKMapView alloc] initWithFrame:self.view.bounds];
map.delegate = self;
[self.view addSubview:map];
}
但是當用戶移動地圖,尋找Walmarts並添加註釋:
- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
// if on slow network, it's useful to keep track of the previous
// search, and cancel it if it still exists
[self.previousSearch cancel];
// create new search request
MKLocalSearchRequest *request = [[MKLocalSearchRequest alloc] init];
request.naturalLanguageQuery = @"Walmart";
request.region = mapView.region;
// initiate new search
MKLocalSearch *localSearch = [[MKLocalSearch alloc] initWithRequest:request];
[localSearch startWithCompletionHandler:^(MKLocalSearchResponse *response, NSError *error) {
NSMutableArray *annotations = [NSMutableArray array];
[response.mapItems enumerateObjectsUsingBlock:^(MKMapItem *item, NSUInteger idx, BOOL *stop) {
// if we already have an annotation for this MKMapItem,
// just return because you don't have to add it again
for (id<MKAnnotation>annotation in mapView.annotations)
{
if (annotation.coordinate.latitude == item.placemark.coordinate.latitude &&
annotation.coordinate.longitude == item.placemark.coordinate.longitude)
{
return;
}
}
// otherwise, add it to our list of new annotations
// ideally, I'd suggest a custom annotation or MKPinAnnotation, but I want to keep this example simple
[annotations addObject:item.placemark];
}];
[mapView addAnnotations:annotations];
}];
// update our "previous" search, so we can cancel it if necessary
self.previousSearch = localSearch;
}
顯然,此代碼示例假定您有一個weak
屬性用於以前的搜索操作。 (這不,嚴格來說,必要的,但如果在地圖上隨便逛逛,當你有一個緩慢的互聯網連接可能會給你更好的性能。)無論如何,該屬性將被定義如下:
@property (nonatomic, weak) MKLocalSearch *previousSearch;
還有其他可能的改進方案(如UIActivityIndicatorView
或網絡活動指示符,如果正在進行搜索,可能會刪除不在地圖當前區域內的註釋等),但希望您能明白。
來源
2013-04-15 19:07:56
Rob
您的初始化也需要改變 - 遵循XCode註釋所說 - 所有的mapview初始化必須在[super viewDidLoad]之後發生。 –
@moomoo - 僅供參考,如果在緩慢的網絡上工作,我已經更新了我的答案,以便在啓動新網絡之前取消先前的搜索(如果還在進行中),請進行更新。 – Rob