#import "ViewController.h"git
#import <MapKit/MapKit.h>数组
#import <CoreLocation/CoreLocation.h>app
// 获取当前版本号ide
#define kCURRENTVERSION [[[UIDevice currentDevice] systemVersion] floatValue]atom
@interface ViewController ()<CLLocationManagerDelegate, UIAlertViewDelegate, UITextFieldDelegate>spa
@property (nonatomic, strong) CLLocationManager *locManager; // 获取当前经纬度code
@property (nonatomic, strong) CLGeocoder *geocoder; // 经过经纬度转换成地址orm
@property (strong, nonatomic) IBOutlet UILabel *longitudeLabel; // 经度事件
@property (strong, nonatomic) IBOutlet UILabel *latitudeLabel; // 纬度ci
@property (strong, nonatomic) IBOutlet UILabel *addressLabel; // 详细地址
@property (strong, nonatomic) IBOutlet UILabel *stateLabel; // 省份
- (IBAction)getAction:(id)sender; // 获取当前经纬度的按钮
@property (strong, nonatomic) IBOutlet UITextField *addressTextField; // 输入地址的textfield
- (IBAction)addressInput:(id)sender; // 根据地址转换成经纬度按钮
@end
@implementation ViewController
#pragma mark 实现懒加载
- (CLLocationManager *)locManager
{
if (_locManager == nil) {
self.locManager = [[CLLocationManager alloc] init];
self.locManager.delegate = self;
}
return _locManager;
}
- (CLGeocoder *)geocoder
{
if (_geocoder == nil) {
self.geocoder = [[CLGeocoder alloc] init];
}
return _geocoder;
}
#pragma mark 页面消失的时候关闭定位
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
// 关闭定位
[self.locManager stopUpdatingLocation];
}
- (void)viewDidLoad {
[super viewDidLoad];
// 初始化设置
self.longitudeLabel.textAlignment = NSTextAlignmentCenter;
self.latitudeLabel.textAlignment = NSTextAlignmentCenter;
self.addressLabel.numberOfLines = 0;
self.addressTextField.delegate = self;
}
- (void)requestWhenInUseAuthorization
{
self.locManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locManager.distanceFilter = 10;
#pragma mark ------------如下二选一---------------
[self.locManager requestWhenInUseAuthorization];//当程序运行的时候获取定位权限
//[self.locManager requestAlwaysAuthorization]; // 程序一直获取定位权限
}
//协议中的方法,做用是每当位置发生更新时会调用的委托方法
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
// 获取数组第一个元素
CLLocation *loc = [locations firstObject];
// 获取经度
self.longitudeLabel.text = [NSString stringWithFormat:@"%f", loc.coordinate.longitude];
// 获取纬度
self.latitudeLabel.text = [NSString stringWithFormat:@"%f", loc.coordinate.latitude];
// 将经纬度转换成地址
[self.geocoder reverseGeocodeLocation:loc completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
// 判断数组是否为空
if (placemarks.count > 0)
{
// 数组不为空
CLPlacemark *placemark = [placemarks objectAtIndex:0];
NSDictionary *dic = placemark.addressDictionary;
// 转换成详细地址
[self getAddress:dic];
//获取城市
NSString *city = placemark.locality;
if (!city) {
//四大直辖市的城市信息没法经过locality得到,只能经过获取省份的方法来得到(若是city为空,则可知为直辖市)
city = placemark.administrativeArea;
}
// 将省份显示
self.stateLabel.text = city;
}
// 地址获取失败
else if (error == nil && [placemarks count] == 0)
{
NSLog(@"No results were returned.");
}
else if (error != nil)
{
NSLog(@"An error occurred = %@", error);
}
}];
[self.locManager stopUpdatingLocation];
}
#pragma mark 获取当前详细地址
- (void) getAddress:(NSDictionary *) addressDic
{
//NSString *state=[addressDic objectForKey:@"State"]; // 省份
NSString *city=[addressDic objectForKey:@"City"]; // 城市
NSString *subLocality=[addressDic objectForKey:@"SubLocality"]; // 区
NSString *street=[addressDic objectForKey:@"Street"]; // 街道
NSString *address = [[city stringByAppendingString:subLocality] stringByAppendingString:street]; // 拼接地址
self.addressLabel.text = address; // 显示地址
}
//当位置获取或更新失败会调用的方法
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSString *errorMsg = nil; // 做为提示框的信息
if ([error code] == kCLErrorDenied) {
errorMsg = @"访问被拒绝,请容许应用获取定位权限";
}
if ([error code] == kCLErrorLocationUnknown) {
errorMsg = @"获取位置信息失败";
}
// 建立提示框
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"定位失败" message:errorMsg preferredStyle:(UIAlertControllerStyleAlert)];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确认" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
// 当应用无权限获取位置信息 从新获取
[self requestWhenInUseAuthorization];
}];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil];
[alertController addAction:cancelAction];
[alertController addAction:okAction];
[self presentViewController:alertController animated:YES completion:nil];
}
#pragma mark 定位失败提示
- (void) showAlert:(NSString *) notice
{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"定位失败" message:notice preferredStyle:(UIAlertControllerStyleAlert)];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确认" style:(UIAlertActionStyleDefault) handler:nil];
[alertController addAction:okAction];
//[self.view addSubview:alertController.view];
[self presentViewController:alertController animated:YES completion:^{
}];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark 获取当前经纬度 button点击事件
- (IBAction)getAction:(id)sender {
// 判断手机定位是否打开
if (kCURRENTVERSION >= 8.0) {
if ([CLLocationManager locationServicesEnabled]) {
[self requestWhenInUseAuthorization];
// 设置距离筛选器distanceFilter,没有筛选器设置
self.locManager.distanceFilter = kCLDistanceFilterNone;
// 精确度 当前选择最精确
self.locManager.desiredAccuracy = kCLLocationAccuracyBest;
[self.locManager startUpdatingLocation];
}
else
{
[self showAlert:@"手机定位未开启"];
}
}
}
#pragma mark 获取地址的经纬度 button点击事件
- (IBAction)addressInput:(id)sender {
NSString *address = self.addressTextField.text;
// 判断地址是否为空
if (address.length == 0) {
[self showAlert:@"地址不能为空"];
return;
}
// 地址不为空 转换成 CLGeocoder 类型
[self.geocoder geocodeAddressString:address completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
if (error || placemarks.count == 0) {
[self showAlert:@"你输入的地址没找到,可能在火星上"];
}
else{
// 取第一个元素
CLPlacemark *firstPlacemark = [placemarks firstObject];
// 获取第一个元素的经纬度
CLLocationCoordinate2D coordinate = firstPlacemark.location.coordinate;
self.longitudeLabel.text = [NSString stringWithFormat:@"%f", coordinate.longitude];
self.latitudeLabel.text = [NSString stringWithFormat:@"%f", coordinate.latitude];
}
}];
}
// 回收键盘
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
@end