CLGeocoder 根据地理位置获取经纬度,根据经纬度获取地理位置

//
//  ViewController.m
//  LocationGenerateCoder
//
//  Created by hq on 16/5/17.
//  Copyright  2016年 hanqing. All rights reserved.
//

#import "ViewController.h"
#import 

@interface ViewController ()

//编码地理位置用的类
@property(nonatomic,strong) CLGeocoder *geo;

@property (weak, nonatomic) IBOutlet UITextView *addressTextView;

@property (weak, nonatomic) IBOutlet UITextField *latitude;

@property (weak, nonatomic) IBOutlet UITextField *longtitude;

- (IBAction)getAddress;

- (IBAction)getDegree;

@end

@implementation ViewController

-(CLGeocoder *)geo{
    
    if (_geo==nil) {
        _geo=[[CLGeocoder alloc] init];
    }
    return _geo;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    

}

//将经纬度转换为我们的地理位置
- (IBAction)getAddress {
    
    CLLocationDegrees lat=[self.latitude.text doubleValue];
    CLLocationDegrees lon=[self.longtitude.text doubleValue];
    
    if ([self.latitude.text length]==0||[self.latitude.text length]==0) {
        NSLog(@"请输入经纬度");
        return;
    }
    
    CLLocation *loc=[[CLLocation alloc]initWithLatitude:lat longitude:lon];

    [self.geo reverseGeocodeLocation:loc completionHandler:^(NSArray * _Nullable placemarks, NSError * _Nullable error) {
       
        if (error) {
            NSLog(@"出错了");
            return ;
        }
        
        for (CLPlacemark *mark in placemarks) {
            
            //获取省
            NSString *state=mark.administrativeArea;
            
            //获取城市
            NSString  *city=mark.locality;
            
            //街道名
            NSString *thoroughfare=mark.thoroughfare;
            
            NSLog(@"%@%@,%@",state,city,thoroughfare);
            
        }
    }];
}

//将地理位置转换为经纬度
- (IBAction)getDegree {
    
    NSString *inputAddress=self.addressTextView.text;
    
    if ([inputAddress length]==0) {
        NSLog(@"请输入正确的地址");
        return;
    }
    
    [self.geo geocodeAddressString:inputAddress completionHandler:^(NSArray * _Nullable placemarks, NSError * _Nullable error) {
        
        
        for (CLPlacemark *mark in placemarks) {
            
            CLLocation *loc=mark.location;
            
            //获取经纬度了
            self.latitude.text=@(loc.coordinate.latitude).stringValue;
            self.longtitude.text=@(loc.coordinate.longitude).stringValue;
            
        }
    }];
    
    /**该方法可以固定一个范围内查找,防止重名的情况
    [self.geo geocodeAddressString:@"北京大学" inRegion:(nullable CLRegion *)
     completionHandler:^(NSArray * _Nullable placemarks, NSError * _Nullable error) {
     
     }];
     */
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}



@end

你可能感兴趣的:(CLGeocoder 根据地理位置获取经纬度,根据经纬度获取地理位置)