iOS - 获取定位

1.在页面引入所需类:

#import 

//定位
@property (nonatomic,strong) AMapLocationManager *LocationManager;
@property (nonatomic,copy) NSString *addressStr;//定位地址
@property (nonatomic,copy) NSString *latitude;//定位纬度
@property (nonatomic,copy) NSString *longitude;//定位经度

2.定位方法:

//定位
-(void)LocationPresent{
    self.LocationManager = [[AMapLocationManager alloc] init];

    // 带逆地理信息的一次定位(返回坐标和地址信息)
    [self.LocationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
    //   定位超时时间,最低5s,此处设置为5s
    self.LocationManager.locationTimeout =5;
    //   逆地理请求超时时间,最低5s,此处设置为5s
    self.LocationManager.reGeocodeTimeout = 5;

    [self.LocationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {

        if (error)
        {
            NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
            if (error.code == AMapLocationErrorLocateFailed)
            {
                return;
            }
        }

        NSLog(@"location:%@", location);
        if (location) {

            // 经纬度
            self.latitude = [NSString stringWithFormat:@"%lf",location.coordinate.latitude];
            self.longitude = [NSString stringWithFormat:@"%lf",location.coordinate.longitude];

        }


        if (regeocode)
        {
            // 详细位置
            NSLog(@"reGeocode:%@", regeocode);
            self.addressStr = [NSString stringWithFormat:@"%@%@%@%@%@%@%@",[self getNullStr:regeocode.country],[self getNullStr:regeocode.province],[self getNullStr:regeocode.city],[self getNullStr:regeocode.district],[self getNullStr:regeocode.street],[self getNullStr:regeocode.number],[self getNullStr:regeocode.POIName]];
            if (self.addressStr.length == 0) {
                self.addressStr = @"未获取";
            }
        }
    }];
}

3.用到的方法(将空字段过滤掉):

- (NSString *)getNullStr:(NSString *)str{

    if (![str isKindOfClass:[NSString class]]) {
        str = [NSString stringWithFormat:@"%@",str];
    }
    
    if ([str isEqualToString:@""] || [str isEqualToString:@"(null)"] || str == nil || [str isKindOfClass:[NSNull class]] || [str isEqualToString:@" "] || [str isEqualToString:@"null"] || [str isEqualToString:@""]) {
        return @"";
    }else{
        return str;
    }
}

你可能感兴趣的:(iOS - 获取定位)