iOS - 获取定位

1.在页面引入所需类:

#import <AMapLocationKit/AMapLocationKit.h>

//定位
@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:@"<null>"]) {
        return @"";
    }else{
        return str;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容