標籤:style blog http ar io color os sp for
1.UI搭建,import標頭檔
#import <CoreLocation/CoreLocation.h>
2.新增成員變數,並連線
1 - (IBAction)geocodeButton; 2 @property (weak, nonatomic) IBOutlet UITextField *inputAddress; 3 @property (weak, nonatomic) IBOutlet UITextField *longitude; 4 @property (weak, nonatomic) IBOutlet UITextField *latitude; 5 @property (weak, nonatomic) IBOutlet UITextView *detailAddress; 6 7 8 - (IBAction)unGeocodeButton; 9 @property (weak, nonatomic) IBOutlet UITextField *reverseLongitude;10 @property (weak, nonatomic) IBOutlet UITextField *reverseLatitude;11 @property (weak, nonatomic) IBOutlet UITextView *reverseDetailAddress;
3.添加地理編碼和反地理編碼的方法
1 /** 2 * 懶載入 3 */ 4 - (CLGeocoder *)geocoder 5 { 6 if (_geocoder == nil) { 7 _geocoder = [[CLGeocoder alloc]init]; 8 } 9 return _geocoder;10 }11 12 /**13 * 鍵盤處理14 */15 - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event16 {17 [self.view endEditing:YES];18 }19 20 /**21 * 地理編碼22 */23 - (IBAction)geocodeButton {24 NSString *address = self.inputAddress.text;25 [self.geocoder geocodeAddressString:address completionHandler:^(NSArray *placemarks, NSError *error) {26 // 地址為空白,直接返回27 if (!address) return ;28 if (error) { // 輸入的地址有錯誤29 self.detailAddress.text = @"你輸入的地址可能不存在";30 }else{31 // 遍曆查詢到的地標32 NSLog(@"總共有%d個地標符合要求",placemarks.count);33 for (int i = 0; i < placemarks.count; i++) {34 CLPlacemark *placemark = placemarks[i];35 NSLog(@"%@",placemark);36 }37 38 // 取地標數組的第一個為最終結果39 CLPlacemark *placemark = [placemarks firstObject];40 self.detailAddress.text = placemark.name;41 self.latitude.text =[NSString stringWithFormat:@"%.1f", placemark.location.coordinate.latitude];42 self.longitude.text = [NSString stringWithFormat:@"%.1f", placemark.location.coordinate.longitude];43 }44 }];45 }46 47 /**48 * 反地理編碼49 */50 - (IBAction)unGeocodeButton {51 // 經緯度轉換52 CLLocationDegrees longitude = [self.reverseLongitude.text doubleValue];53 CLLocationDegrees latitude = [self.reverseLatitude.text doubleValue];54 CLLocation *location = [[CLLocation alloc]initWithLatitude:latitude longitude:longitude];55 56 // 反地理編碼57 [self.geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {58 if (location == nil) return;59 if (error) {60 NSLog(@"你輸入的經緯度有誤");61 }else{62 // 遍曆地標數組63 NSLog(@"總共有%d個地標符合要求",placemarks.count);64 for (int i; i < placemarks.count; i++) {65 CLPlacemark *placemark = placemarks[i];66 NSLog(@"%@",placemark);67 }68 69 // 取地標數組的第一個為最終結果70 CLPlacemark *placemark =[placemarks firstObject];71 self.reverseDetailAddress.text = placemark.name;72 }73 74 }];75 }
iOS 地理編碼和反地理編碼