IOS中定位当前所在城市

在项目中要用到定位所在地的功能,这里大致说下我的做法:

首先要使用定位,需要在所在的类#import <MapKit/MapKit.h>  ,然后继承协议CLLocationManagerDelegate,在.h类定义CLLocationManager* _locationManager;

CLGeocoder*  _currentCityGeocoder;


在.m类中实现:   

     _currentCityGeocoder = [[CLGeocoder alloc] init];
       _locationManager = [[CLLocationManager alloc] init];
       _locationManager.delegate = self;
     _locationManager.distanceFilter = 1000.0f;//用来控制定位服务更新频率。单位是“米”
       _locationManager.desiredAccuracy = kCLLocationAccuracyBest;//这个属性用来控制定位精度,精度越高耗电量越大。
      [_locationManager startUpdatingLocation];
然后实现代理方法:

#pragma mark - mapDelegate
 -(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
 [_locationManager stopUpdatingLocation];
 NSString *strLat = [NSString stringWithFormat:@"%.4f",newLocation.coordinate.latitude];
 NSString *strLng = [NSString stringWithFormat:@"%.4f",newLocation.coordinate.longitude];
 NSLog(@"Lat: %@  Lng: %@", strLat, strLng);
 [_currentCityGeocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
 CLPlacemark* placeMark = [placemarks objectAtIndex:0];
 NSString*  currentCityStr = [placeMark locality];
 NSLog(@"当前省份为:%@",placeMark.administrativeArea);
 NSLog(@"当前城市为:%@",currentCityStr);
 _currentLocationLabel.text = [placeMark.administrativeArea stringByAppendingFormat:@"  %@",currentCityStr];
 [self.progress dismiss];
 //        _locationLabel.text = placeMark.administrativeArea;
 // we have received our current location, so enable the "Get Current Address" button
 }];
 
 }
 - (void)locationManager:(CLLocationManager *)manager
 didFailWithError:(NSError *)error
 {
 // Failed to receive user's location
 
 NSString *errorMsg = nil;
 if ([error code] == kCLErrorDenied) {
 errorMsg = @"访问被拒绝";
 }
 if ([error code] == kCLErrorLocationUnknown) {
 errorMsg = @"获取位置信息失败";
 }
 
 UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"Location"
 message:errorMsg delegate:self cancelButtonTitle:@"Ok"otherButtonTitles:nil, nil];
 [alertView show];
 }
这样即可实现简单的定位。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值