iOS 调用系统原生的定位

苹果手机在中国使用的是高德地图,所以调用iOS系统原生的定位其实使用的就是高德的定位。

1、添加定位需要的头文件

#import <CoreLocation/CoreLocation.h>

2、定位需要遵循的代理

CLLocationManagerDelegate

3、获取经纬度的代码

-(void)getLocation
{
    locationmanager = [[CLLocationManager alloc] init];
    [locationmanager requestWhenInUseAuthorization];
    locationmanager.delegate = self;
    [locationmanager requestAlwaysAuthorization];

    locationmanager.desiredAccuracy = kCLLocationAccuracyBest;
    locationmanager.distanceFilter = 5.0;
    [locationmanager startUpdatingLocation];
    
}

#pragma mark 定位成功后则执行此代理方法
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    [locationmanager stopUpdatingLocation];
    CLLocation *currentLocation = [locations lastObject];
    NSLog(@"%f,%f",currentLocation.coordinate.latitude,currentLocation.coordinate.longitude);
}

/** 定位服务状态改变时调用*/
-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    if (status == kCLAuthorizationStatusDenied) {
        // 类方法,判断是否开启定位服务
        if ([CLLocationManager locationServicesEnabled]) {
            [self openLocationServices];
            NSLog(@"定位服务开启,被拒绝");
        } else {
            NSLog(@"定位服务关闭,不可用");
        }
    }
}

- (void)openLocationServices
{
    [PXAlertView showAlertWithTitle:@"无法使用定位权限"
                            message:@"请在设置页面中打开定位权限"
                        cancelTitle:@"取消"
                         otherTitle:@"确定"
                         completion:^(BOOL cancelled, NSInteger buttonIndex) {
                             [self.navigationController popToRootViewControllerAnimated:YES];
                         }];
}

猜你喜欢

转载自blog.csdn.net/u010545480/article/details/100916299