地理编码与反地理编码

            地理编码是把某个具体的位置计算为经纬度,反地理编码正好相反。

            效果:通过输入框的搜索,也能定位到具体的位置。长按地图,就能获得某个位置的详细地址。

  1. #import "ViewController.h"  
  2. #import   
  3.   
  4. @interface ViewController ()  
  5.   
  6. @property (nonatomicstrongMKMapView * mapView;  
  7. @property (nonatomicstrongCLLocationManager * locationManager;  
  8. @property (nonatomicstrongUITextField * textField;  
  9. @property (nonatomicstrongNSString * titleString;  
  10.   
  11. @end  
  12.   
  13. @implementation ViewController  
  14.   
  15. - (void)viewDidLoad {  
  16.     [super viewDidLoad];  
  17.   
  18. //    116.456011,39.941272  
  19.     _mapView = [[MKMapView alloc] initWithFrame:self.view.bounds];  
  20.     [_mapView setDelegate:self];  
  21.     [_mapView setShowsUserLocation:YES];  
  22.     [_mapView setMapType:MKMapTypeStandard];  
  23.     [self.view addSubview:_mapView];  
  24.       
  25.     UILongPressGestureRecognizer * longpressGestureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressed:)];  
  26.     [_mapView addGestureRecognizer:longpressGestureRecognizer];  
  27.       
  28.     _textField = [[UITextField alloc] init];  
  29.     [_textField setTranslatesAutoresizingMaskIntoConstraints:NO];  
  30.     [_textField setBackgroundColor:[UIColor whiteColor]];  
  31.     [self.view addSubview:_textField];  
  32.       
  33.     UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];  
  34.     [btn setBackgroundColor:[UIColor orangeColor]];  
  35.     [btn setTitle:@"查找" forState:UIControlStateNormal];  
  36.     [btn setTranslatesAutoresizingMaskIntoConstraints:NO];  
  37.     [btn addTarget:self action:@selector(theBtnPressed:) forControlEvents:UIControlEventTouchUpInside];  
  38.     [self.view addSubview:btn];  
  39.       
  40.     [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-20-[_textField][btn(100)]-20-|"  
  41.                                                                      options:0  
  42.                                                                      metrics:nil  
  43.                                                                         views:NSDictionaryOfVariableBindings(_textField,btn)]];  
  44.     [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-20-[_textField(30)]-(-30)-[btn(30)]"  
  45.                                                                       options:0  
  46.                                                                       metrics:nil  
  47.                                                                         views:NSDictionaryOfVariableBindings(_textField,btn)]];  
  48.       
  49.     //检测定位功能是否开启  
  50.     if([CLLocationManager locationServicesEnabled]){  
  51.           
  52.         if(!_locationManager){  
  53.              
  54.             _locationManager = [[CLLocationManager alloc] init];  
  55.               
  56.             if([_locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]){  
  57.                 [_locationManager requestWhenInUseAuthorization];  
  58.                 [_locationManager requestAlwaysAuthorization];  
  59.                   
  60.             }  
  61.   
  62.             //设置代理  
  63.             [_locationManager setDelegate:self];  
  64.             //设置定位精度  
  65.             [_locationManager setDesiredAccuracy:kCLLocationAccuracyBest];  
  66.             //设置距离筛选  
  67.             [_locationManager setDistanceFilter:100];  
  68.             //开始定位  
  69.             [_locationManager startUpdatingLocation];  
  70.             //设置开始识别方向  
  71.             [_locationManager startUpdatingHeading];  
  72.               
  73.         }  
  74.           
  75.     }else{  
  76.         UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:nil  
  77.                                                              message:@"您没有开启定位功能"  
  78.                                                             delegate:nil  
  79.                                                    cancelButtonTitle:@"确定"  
  80.                                                    otherButtonTitles:nil, nil nil];  
  81.         [alertView show];  
  82.     }  
  83. }  
  84.   
  85. //点击按钮执行此方法  
  86. - (void)theBtnPressed:(id)sender {  
  87.     [_textField resignFirstResponder];  
  88.     if([_textField.text length] == 0){  
  89.           
  90.         return;  
  91.     }  
  92.     [self geocoder:_textField.text];  
  93. }  
  94.   
  95. #pragma mark LongPress  
  96. - (void)longPressed:(UILongPressGestureRecognizer *)recognizer {  
  97.     if(recognizer.state == UIGestureRecognizerStateBegan){  
  98.         CGPoint point = [recognizer locationInView:_mapView];  
  99.         CLLocationCoordinate2D coordinate2D = [_mapView convertPoint:point toCoordinateFromView:_mapView];  
  100.           
  101.         [_mapView removeAnnotations:_mapView.annotations];  
  102.           
  103.         CLLocation * location = [[CLLocation alloc] initWithLatitude:coordinate2D.latitude longitude:coordinate2D.longitude];  
  104.           
  105.         [self reverseGeocoder:location];  
  106.           
  107. //        MKPointAnnotation * pointAnnotation = [[MKPointAnnotation alloc] init];  
  108. //        [pointAnnotation setTitle:_titleString];  
  109. //        [pointAnnotation setCoordinate:coordinate2D];  
  110. //        [_mapView addAnnotation:pointAnnotation];  
  111.     }  
  112. }  
  113.   
  114. //授权状态发生改变的时候执行  
  115. - (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {  
  116.     switch(status){  
  117.         case kCLAuthorizationStatusDenied:  
  118.         {  
  119.             UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:nil  
  120.                                                                  message:@"定位功能没有开启" delegate:nil  
  121.                                                        cancelButtonTitle:@"确定" otherButtonTitles:nil, nil nil];  
  122.             [alertView show];  
  123.         }  
  124.             break;  
  125.         default:  
  126.             break;  
  127.     }  
  128. }  
  129.   
  130. #pragma mark mapViewDelegate   
  131. - (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id)annotation{  
  132.     static NSString * key = @"key";  
  133.     MKPinAnnotationView * pinAnnotationView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:key];  
  134.       
  135.     if(pinAnnotationView == nil){  
  136.         pinAnnotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:key];  
  137.         [pinAnnotationView setCanShowCallout:YES];  
  138.     }  
  139.       
  140.     if([annotation isKindOfClass:[MKUserLocation class]]){  
  141.         [pinAnnotationView setPinColor:MKPinAnnotationColorRed];  
  142.         [((MKUserLocation *)annotation) setTitle:_titleString];  
  143.     }else{  
  144.         [pinAnnotationView setPinColor:MKPinAnnotationColorPurple];  
  145.     }  
  146.       
  147.     return pinAnnotationView;  
  148. }  
  149.   
  150. #pragma mark - CLLocationManangerDelegate  
  151. //定位成功以后调用  
  152. - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {  
  153.     [_locationManager stopUpdatingLocation];  
  154.     CLLocation * location = locations.lastObject;  
  155.       
  156.     MKCoordinateRegion coordinateRegion = MKCoordinateRegionMake(CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude), MKCoordinateSpanMake(0.10.1));  
  157.       
  158.     [_mapView setRegion:[_mapView regionThatFits:coordinateRegion] animated:YES];  
  159.       
  160. //    [self reverseGeocoder:location];  
  161. }  
  162.   
  163. - (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {  
  164.     NSLog(@"error:%@",error);  
  165. }  
  166.   
  167.   
  168. #pragma mark Geocoder  
  169. //反地理编码  
  170. - (void)reverseGeocoder:(CLLocation *)currentLocation {  
  171.       
  172.     CLGeocoder * geocoder = [[CLGeocoder alloc] init];  
  173.     [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {  
  174.       
  175.         if(error || placemarks.count == 0){  
  176.             NSLog(@"error");  
  177.         }else{  
  178.               
  179.             CLPlacemark * placemark = placemarks.firstObject;  
  180.               
  181.             self.titleString = placemark.name;  
  182.             MKPointAnnotation * pointAnnotation = [[MKPointAnnotation alloc] init];  
  183.             [pointAnnotation setTitle:placemark.name];  
  184.             [pointAnnotation setCoordinate:CLLocationCoordinate2DMake(placemark.location.coordinate.latitude, placemark.location.coordinate.longitude)];  
  185.             [_mapView addAnnotation:pointAnnotation];  
  186.               
  187.             NSLog(@"placemark:%@",[[placemark addressDictionary] objectForKey:@"City"]);  
  188.         }  
  189.           
  190.     }];  
  191. }  
  192.   
  193. //地理编码  
  194. - (void)geocoder:(NSString *)str {  
  195.     CLGeocoder * geocoder = [[CLGeocoder alloc] init];  
  196.     [geocoder geocodeAddressString:str completionHandler:^(NSArray *placemarks, NSError *error) {  
  197.          
  198.         if(error || placemarks.count == 0){  
  199.             NSLog(@"error");  
  200.         }else{  
  201.             CLPlacemark * placemark = placemarks.firstObject;  
  202.             MKCoordinateRegion coordinateRegion = MKCoordinateRegionMake(CLLocationCoordinate2DMake(placemark.location.coordinate.latitude, placemark.location.coordinate.longitude), MKCoordinateSpanMake(0.10.1));  
  203.               
  204.             [_mapView setRegion:[_mapView regionThatFits:coordinateRegion] animated:YES];  
  205.               
  206.             MKPointAnnotation * pointAnnotation = [[MKPointAnnotation alloc] init];  
  207.             [pointAnnotation setTitle:placemark.name];  
  208.             [pointAnnotation setCoordinate:CLLocationCoordinate2DMake(placemark.location.coordinate.latitude, placemark.location.coordinate.longitude)];  
  209.             [_mapView addAnnotation:pointAnnotation];  
  210.         }  
  211.           
  212.     }];  
  213. }  
  214.   
  215. - (void)didReceiveMemoryWarning {  
  216.     [super didReceiveMemoryWarning];  
  217.     // Dispose of any resources that can be recreated.  
  218. }  
  219.   
  220. @end

           参考:http://blog.csdn.net/chenyufeng1991/article/details/48596791

  

你可能感兴趣的:(地理编码与反地理编码)