標籤:
- (void)viewDidLoad
{
[super viewDidLoad];
self.geocoder = [[CLGeocoder alloc]init];
// 設定地圖可縮放
self.mapView.zoomEnabled = YES;
// 設定地圖可滾動
self.mapView.scrollEnabled = YES;
// 設定地圖不可旋轉
self.mapView.rotateEnabled = NO;
// 設定顯示使用者當前位置
self.mapView.showsUserLocation = YES;
// 設定地圖的類型
self.mapView.mapType = MKMapTypeStandard;
// 為了方便測試,直接設定搜尋方塊的常值內容
self.searchBar.text [email protected]"北京動物園";
self.searchBar.delegate = self;
}
// 當使用者單擊虛擬鍵盤上的“搜尋”按鈕時激發該方法
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
// 調用searchBar方法進行搜尋
[self doSearch:searchBar];
}
// 當使用者單擊“取消”按鈕時激發該方法
// 由於我們重定義了該控制項的外觀——將取消按鈕的文本改成了“搜尋”,因此單擊取消按鈕也執行搜尋
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
// 調用searchBar方法進行搜尋
[self doSearch:searchBar];
}
// 執行搜尋的方法
- (void)doSearch:(UISearchBar *)searchBar
{
// 關閉searchBar關聯的虛擬鍵盤
[self.searchBar resignFirstResponder];
NSString* searchText = self.searchBar.text;
if(searchText != nil && searchText.length > 0)
{
[self locateAt:searchText];
}
}
// 當使用者在搜尋方塊內輸入文本時激發該方法
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
// 顯示取消按鈕
searchBar.showsCancelButton = YES;
// 通過遍曆找到該搜尋方塊內的取消按鈕,並將取消按鈕的文本設為“搜尋”
for (id cc in [searchBar.subviews[0] subviews])
{
if ([cc isKindOfClass:[UIButton class]])
{
UIButton *button = (UIButton *)cc;
[button setTitle:@"搜尋" forState:UIControlStateNormal];
}
}
}
// 將字串地址轉換為經度、緯度資訊,並執行定位
-(void)locateAt:(NSString*)address
{
[self.geocoder geocodeAddressString:address completionHandler:
^(NSArray *placemarks, NSError *error)
{
if ([placemarks count] > 0 && error == nil)
{
NSLog(@"搜尋到匹配%lu條地址資料.", (unsigned long)placemarks.count);
// 處理第一個地址
CLPlacemark * placemark = [placemarks objectAtIndex:0];
NSLog(@"經度 = :%f", placemark.location.coordinate.longitude);
NSLog(@"緯度 = :%f", placemark.location.coordinate.latitude);
NSLog(@"國家 = %@", placemark.country);
NSLog(@"郵編 = %@", placemark.postalCode);
NSLog(@"位置 = %@", placemark.locality);
// 設定地圖顯示的範圍
MKCoordinateSpan span;
// 地圖顯示範圍越小,細節越清楚
span.latitudeDelta = 0.01;
span.longitudeDelta = 0.01;
MKCoordinateRegion region = {placemark.location.coordinate,span};
// 設定地圖中心位置為搜尋到的位置
[self.mapView setRegion:region]; // ①
// 建立一個MKPointAnnotation,該對象將作為地圖錨點
MKPointAnnotation *point = [[MKPointAnnotation alloc]init];
// 設定地圖錨點的座標
point.coordinate = placemark.location.coordinate;
// 設定地圖錨點的標題
point.title = placemark.name;
// 設定地圖錨點的副標題
point.subtitle = [NSString stringWithFormat:@"%@-%@-%@-%@",
placemark.country , placemark.administrativeArea,
placemark.locality , placemark.subLocality];
// 將地圖錨點添加到地圖上
[self.mapView addAnnotation:point];
// 選中指定錨點
[self.mapView selectAnnotation:point animated:YES];
}
else
{
NSLog(@"沒有搜尋到匹配資料");
}
}];
}
iOS 根據字串來定位地址