iOS获取定位的方式(百度和系统自带的定位方式)

本文介绍了在iOS中获取用户定位的方法,包括设置info.plist文件,使用系统定位服务以及集成百度地图SDK获取经纬度。同时,文章涵盖了处理定位权限提示、更新位置信息以及如何获取城市名的细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 首先在info.plist文件中设置

NSLocationAlwaysUsageDescription   string  我们需要您当前所在位置喔  //始终获取

NSLocationWhenInUseUsageDescription  string  我们需要您当前所在位置喔  //在使用应用期间

2. 设置系统和百度的定位方式

1) 系统定位

//头文件中加入delegate

@property (nonatomic,retain)CLLocationManager  *locationManager;

//.m文件中创建

//iOS自带定位,获取经纬度

- (void)createLocationManage

{

    self.locationManager = [[CLLocationManager alloc]init];

    self.locationManager.delegate = self;

    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;

    self.locationManager.distanceFilter = 10;

    [CLLocationManager locationServicesEnabled];

    

    if ([[[UIDevice currentDevice] systemVersion] floatValue]>=8.0) {

        [self.locationManager requestAlwaysAuthorization];//如果想让ios8获取当前地址,需要添加此代码

    }

    [self.locationManager startUpdatingLocation];

    

    if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) {

        NSLog(@"定位不可用");

        [self shopsList:@" " setLat:@" "];

    }

}


#pragma mark CLLocationManager

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations

{

    CLLocation *currLocation = [locations lastObject];

    

    localLongitude = currLocation.coordinate.longitude;

    localLatitude  = currLocation.coordinate.latitude;

    

    

    NSString *localLongitudeStr = [NSString stringWithFormat:@"%f",localLongitude]; //经度

    NSString *localLatitudeStr  = [NSString stringWithFormat:@"%f",localLatitude];  //维度

    

    //将经纬度保存到SharedInfo

    SharedInfo *sharedInfo = [SharedInfo sharedDataInfo];

    sharedInfo.localLongitude = localLongitudeStr;

    sharedInfo.localLatitude  = localLatitudeStr;

    

    

    //NSLog(@"localLongitudeStr:%@",localLongitudeStr);

    //NSLog(@"localLatitudeStr:%@",localLatitudeStr);

    

    [self.locationManager stopUpdatingLocation];

    

    

    //获取当前城市名

    CLGeocoder *geocoder = [[CLGeocoder alloc]init];

    [geocoder reverseGeocodeLocation:currLocation completionHandler:^(NSArray *placemarks, NSError *error) {

        

        for (CLPlacemark *place in  placemarks) {

            //NSLog(@"name,%@",place.name);                        //位置

            //NSLog(@"thoroughfare,%@",place.thoroughfare);        //街道

            //NSLog(@"subThoroughfare,%@",place.subThoroughfare);  //子街道

            if (place != nil) {

                NSString *tempCity = place.locality;

                _currentLocation = [tempCity stringByReplacingOccurrencesOfString:@"" withString:@""];

                

                sharedInfo.currentCity = _currentLocation;

                if (sharedInfo.currentCity.length > 0) {

                    if (sharedInfo.subCityName.length > 0) {

                        NSString  *cityNames = [NSString stringWithFormat:@"%@-%@",sharedInfo.currentCity,sharedInfo.subCityName];

                        [self createLeftBtn:cityNames];

                    }else{

                        [self createLeftBtn:sharedInfo.currentCity];

                    }

                }

                

                [self getAllCityList];

                [self shopsList:localLongitudeStr setLat:localLatitudeStr];

                //NSLog(@"locality,%@",_currentLocation);            //

                return;

            }

            //NSLog(@"subLocality,%@",place.subLocality);          //

            //NSLog(@"country,%@",place.country);                  //国家

        }

    }];

}


//根据错误号,如果不允许定位的时候处理方法

- (void)locationManager: (CLLocationManager *)manager

       didFailWithError: (NSError *)error {

    

    [manager stopUpdatingLocation];

    if ([error code] == 1) {

        if (IS_IOS7) {

            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"定位服务未开启" message:@"定位服务已被关闭,请前往设置页面打开" delegate:self cancelButtonTitle:@"暂不" otherButtonTitles:nil, nil];

            alertView.tag = 1101;

            [alertView show];

        }else if (IS_IOS8){

            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"定位服务未开启" message:@"定位服务已被关闭,请前往设置页面打开" delegate:self cancelButtonTitle:@"暂不" otherButtonTitles:@"去设置", nil];

            alertView.tag = 1100;

            [alertView show];

        }

    }

}


2) 百度定位

//百度地图获取经纬度

- (void)createBaiDuMapView

{

    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];

    if (IS_IOS7) {

        if (kCLAuthorizationStatusDenied == status || kCLAuthorizationStatusRestricted == status) {

            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"定位服务未开启" message:@"定位服务已被关闭,请前往设置页面打开" delegate:self cancelButtonTitle:@"暂不" otherButtonTitles:nil, nil];

            alertView.tag = 1101;

            [alertView show];

        }

    }else if (IS_IOS8){

        if (kCLAuthorizationStatusDenied == status || kCLAuthorizationStatusRestricted == status) {

            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"定位服务未开启" message:@"定位服务已被关闭,请前往设置页面打开" delegate:self cancelButtonTitle:@"暂不" otherButtonTitles:@"去设置", nil];

            alertView.tag = 1100;

            [alertView show];

        }

    }

    

    [self initMBProgress:@"数据加载中..."];

    //设置定位精确度,默认:kCLLocationAccuracyBest

    [BMKLocationService setLocationDesiredAccuracy:kCLLocationAccuracyBest];

    //指定最小距离更新(),默认:kCLDistanceFilterNone

    [BMKLocationService setLocationDistanceFilter:100.f];  //当距离超过100米的时候就更新一次地图

    

    //初始化BMKLocationService

    _locService = [[BMKLocationService alloc]init];

    _locService.delegate = self;

    //启动LocationService

    [_locService startUserLocationService];

}

#pragma mark -- BaiDuMapDelegate

//处理位置坐标更新

- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation

{

    //NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);

    //这里通过百度和系统自带的定位方式来获取经纬度,如果系统没有获取到,就获取百度的

    localLongitude = userLocation.location.coordinate.longitude;

    localLatitude  = userLocation.location.coordinate.latitude;

    

    NSString *localLongitudeStr = [NSString stringWithFormat:@"%f",localLongitude]; //经度

    NSString *localLatitudeStr  = [NSString stringWithFormat:@"%f",localLatitude];  //维度

    

    //将经纬度保存到SharedInfo

    SharedInfo *sharedInfo = [SharedInfo sharedDataInfo];

    sharedInfo.localLongitude = localLongitudeStr;

    sharedInfo.localLatitude  = localLatitudeStr;

    

    // 保存 Device 的现语言 (英语 法语)

    NSMutableArray *userDefaultLanguages = [[NSUserDefaults standardUserDefaults]

                                            objectForKey:@"AppleLanguages"];

    // 强制 简体中文

    [[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"zh-hans",nil]

                                              forKey:@"AppleLanguages"];

    

    

    CLGeocoder *Geocoder=[[CLGeocoder alloc]init];//CLGeocoder用法参加之前博客

    CLGeocodeCompletionHandler handler = ^(NSArray *place, NSError *error) {

        for (CLPlacemark *placemark in place) {

            cityStr=placemark.name;

            cityName=placemark.locality;

            

            NSLog(@"city %@",placemark.name); //获取街道地址

            NSLog(@"cityName %@",placemark.locality);//获取城市名

            

            NSString *tempCity = placemark.locality;

            _currentLocation = [tempCity stringByReplacingOccurrencesOfString:@"市市辖区" withString:@""];

            _currentLocation = [tempCity stringByReplacingOccurrencesOfString:@"" withString:@""];

            

            sharedInfo.currentCity = _currentLocation;

            

            if (sharedInfo.currentCity.length > 0) {

                if (sharedInfo.subCityName.length > 0) {

                    NSString  *cityNames = [NSString stringWithFormat:@"%@-%@",sharedInfo.currentCity,sharedInfo.subCityName];

                    [self createLeftBtn:cityNames];

                }else{

                    [self createLeftBtn:sharedInfo.currentCity];

                }

            }

            sharedInfo.cityName = placemark.name;

            [self getAllCityList];

            [self shopsList:localLongitudeStr setLat:localLatitudeStr];

        }

    };

    

    CLLocation *loc = [[CLLocation alloc] initWithLatitude:userLocation.location.coordinate.latitude longitude:userLocation.location.coordinate.longitude];

    [Geocoder reverseGeocodeLocation:loc completionHandler:handler];

    

    NSLog(@"百度地图经纬度:%f ... %f",userLocation.location.coordinate.latitude, userLocation.location.coordinate.longitude);

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值