iOS获取当前位置经纬度

最近在做一个公交车查询的项目,需要定位到当前位置以便进行附近站点查询,和大家分享一下怎样获取自己当前位置的经纬度

首先添加CoreLocation.framework库:


引用头文件并声明CLLocationManagerDelegate代理:

接下来声明要用到的变量:

@property (strong, nonatomic) CLLocationManager *locManager;
@property (strong, nonatomic) CLLocation *checkinLocation;
@property (strong, nonatomic) NSString *currentLatitude; //纬度
@property (strong, nonatomic) NSString *currentLongitude; //经度

在viewDidLoad中判断用户是否启用定位服务,第一次进入应用时系统会提示是否启用定位操作。然后开始定位当前位置:

if ([CLLocationManager locationServicesEnabled]) {
        self.locManager = [[CLLocationManager alloc] init];
        self.locManager.delegate = self;
    }else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"警告" message:@"无法进行定位操作" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }
    [self.locManager startUpdatingLocation];

调用代理方法更新当前位置:

扫描二维码关注公众号,回复: 3954481 查看本文章

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    self.checkinLocation = [locations lastObject];
    CLLocationCoordinate2D cool = self.checkinLocation.coordinate;
    self.currentLatitude  = [NSString stringWithFormat:@"%.4f",cool.latitude];
    self.currentLongitude = [NSString stringWithFormat:@"%.4f",cool.longitude];
    
    NSLog(@"%@,%@",self.currentLatitude,self.currentLongitude);
}

运行程序,控制台也输出了当前位置的经纬度(遮住地址,写的不好你们也找不到我):


第一次写博客,希望能对大家有所帮助,有错误和不足的地方希望大家能提提意见,学习的路上与大家共勉,我可是励志要成为火星猿的男人!

猜你喜欢

转载自blog.csdn.net/crypond/article/details/42642289
今日推荐