iOS地理位置使用

iOS地理位置使用

经纬度介绍

英语不好,老是分不开这两个单词,在这记录一下。

经度:longitude,竖线,(long有纵向之意,用来表示经度)
纬度:latitude,

使用

1.在项目导入 CoreLocation.framework

2.申请用户授权(ios 8之后才需要)。在info.plist文件中添加一个键:
NSLocationAlwaysUsageDescription或者NSLocationWhenInUseUsageDescription。其中NSLocationAlwaysUsageDescription是要始终使用定位服务,NSLocationWhenInUseUsageDescription是只在前台使用定位服务。
分别对应的授权方法为:

- (void)requestAlwaysAuthorization; - (void)requestWhenInUseAuthorization; 

3.初始化,代码如下:

    //创建地理位置管理对象
    self.locationManager = [[CLLocationManager alloc] init];
    //申请授权
    [self.locationManager requestAlwaysAuthorization];
    //设置管理器委托
    self.locationManager.delegate = self;
    //设置精度
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    //启动位置管理器
    [self.locationManager startUpdatingLocation];

4.实现委托方法

//地理位置发生更新时
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    //如果在一段比较短的时间发生了多次位置更新,这几次位置更新有可能会被一次性全部上报。无论何时,最后一项表示当前位置
    CLLocation *newLocation = [locations lastObject];
    
    //显示纬度
    NSString *latitudeString = [NSString stringWithFormat:@"%g\u00B0",newLocation.coordinate.latitude];
    self.latitudeLabel.text = latitudeString;
    
    //显示经度
    NSString *longitudeString = [NSString stringWithFormat:@"%g\u00B0",newLocation.coordinate.longitude];
    self.longitudeLabel.text = longitudeString;
    
    //显示水平精度
    NSString *horizontalAccuracyString = [NSString stringWithFormat:@"%gm",newLocation.horizontalAccuracy];
    self.horizontalAccuracyLabel.text = horizontalAccuracyString;
    
    //显示海拔高度
    NSString *altitudeString = [NSString stringWithFormat:@"%gm",newLocation.altitude];
    self.altitudeLabel.text = altitudeString;
    
    //显示垂直精度
    NSString *verticalAccuracyString = [NSString stringWithFormat:@"%gm",newLocation.verticalAccuracy];
    self.verticalAccuracyLabel.text = verticalAccuracyString;
    
    if (newLocation.verticalAccuracy < 0 || newLocation.horizontalAccuracy < 0) {
        return;
    }
    
    if (newLocation.horizontalAccuracy > 100 || newLocation.verticalAccuracy > 50) {
        return;
    }
    
    if (self.previousPoint == nil) {
        return;
    } else {
        self.totalMovementDistance += [newLocation distanceFromLocation:self.previousPoint];
    }
    self.previousPoint = newLocation;
    
    NSString *distanceString = [NSString stringWithFormat:@"%gm",self.totalMovementDistance];
    self.distanceTraveledLabel.text = distanceString;

}

//获取地理位置失败时
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    NSString *errorType = (error.code == kCLErrorDenied) ? @"Access Denied": @"Unknown Error";
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error getting Location" message:errorType delegate:nil cancelButtonTitle:@"Okay" otherButtonTitles:nil];
    [alert show];
}

代码下载

https://github.com/limaofuyuanzhang/WhereAmI

参考

iOS定位服务的应用
《精通iOS开发(第6版)》第19章 Core Location和Map Kit

你可能感兴趣的:(地理位置)