ios系统经纬度转百度经纬度及经纬度转地址

       正在进行的项目中有这样的需求:定位获得当前经纬度,再用百度Place API使用经纬度查询周边信息。这里不需要显示地图,只需要定位。看似思路很顺畅,做起来却不容易。

      iPhone的GPS定位(CLLocationManager)获得的经纬坐标是基于WGS-84坐标系(世界标准),Google地图使用的是GCJ-02坐标系(中国特色的火星坐标系),这就是为什么获得的经纬坐标在google地图上会发生偏移。我项目需求是使用百度Place API,百度的经纬坐标在GCJ-02的基础上再做了次加密,就是DB-09坐标系。就想使用百度地图的IOS SDK,里面的坐标系统都是一致的而不用转换,由于不想让项目太大,所以没有用百度的sdk,所以另辟蹊径了。

       在网上搜索一番,有现成百度的接口转换坐标,经试验 从WGS-84到GCJ-02,再到DB-09,经两次转换后,顺利获得当前正确地理位置信息和周边信息,当然这些信息是来自百度的。

ZYLocationManager.h

#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>
#import "Singleton.h"

typedef void(^locationBlock)(CLLocationCoordinate2D coor);
typedef void(^addressBlock)(NSString *address);

@interface ZYLocationManager : NSObject
singleton_interface(ZYLocationManager)

/**
 *  获取纠偏后的经纬度(百度地图经纬度)
 */
- (void) getLocationCoordinate:(locationBlock) locaiontBlock;

/**
 *  获取纠偏后的经纬度(百度地图经纬度)和地址
 */
- (void) getLocationCoordinate:(locationBlock) locaiontBlock address:(addressBlock) addressBlock;

@end

ZYLocationManager.m

#import "ZYLocationManager.h"
#import "AFNetworking.h"
#define IOS_Version [[UIDevice currentDevice].systemVersion floatValue]
@interface ZYLocationManager ()<CLLocationManagerDelegate>{
// 保存block
    locationBlock _locationBlock;
    addressBlock _addressBlock;
}

@property (nonatomic, strong) CLLocationManager *lm;

@end

@implementation ZYLocationManager
singleton_implementation(ZYLocationManager)

/**
 *  懒加载
 */
- (CLLocationManager *)lm
{
    if (!_lm) {
        _lm = [[CLLocationManager alloc] init];
        _lm.delegate = self;
        // 定位精准度
        _lm.desiredAccuracy = kCLLocationAccuracyBest;
        // 重新定位的距离
        _lm.distanceFilter = 1000.0f;
    }
    return _lm;
}

/**
 *  类第一次使用的时候被调用
 */
+ (void)initialize
{
    ZYLocationManager *manager = [self sharedZYLocationManager];
    // ios8后需要向用户请求权限
    if (IOS_Version >= 8.0) {
        [manager.lm requestWhenInUseAuthorization];
        [manager.lm requestAlwaysAuthorization];
    }
    // 开始定位
    [manager.lm startUpdatingLocation];
}

#pragma mark - CLLocationManager获取经纬度的代理方法
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation *location = [locations lastObject];
    CLLocationCoordinate2D coor = location.coordinate;
//    NSLog(@"纬度:%.6f 经度%.6f", coor.latitude, coor.longitude);
    NSString *x1 = [NSString stringWithFormat:@"%f", coor.longitude];
    NSString *y1 = [NSString stringWithFormat:@"%f", coor.latitude];
    // http://api.map.baidu.com/ag/coord/convert?from=0&to=2&x=113.377346&y=23.132648
    __block NSDictionary *dict1 = @{@"from":@"0",
                            @"to":@"2",
                            @"x":x1,
                            @"y":y1
                            };
    AFHTTPRequestOperationManager *roManager = [AFHTTPRequestOperationManager manager];
    // 1、ios系统经纬度(国际标准)转谷歌经纬度
    [roManager GET:@"http://api.map.baidu.com/ag/coord/convert" parameters:dict1 success:^(AFHTTPRequestOperation *operation, id responseObject) {
        __block NSString *resultX = [self base64Decode:responseObject[@"x"]];
        __block NSString *resultY = [self base64Decode:responseObject[@"y"]];
        dict1 = @{@"from":@"2",
                  @"to":@"4",
                  @"x":resultX,
                  @"y":resultY
                  };
        
        // 2、谷歌经纬度转百度经纬度
        [roManager GET:@"http://api.map.baidu.com/ag/coord/convert" parameters:dict1 success:^(AFHTTPRequestOperation *operation, id responseObject) {
            resultX = [self base64Decode:responseObject[@"x"]];
            resultY = [self base64Decode:responseObject[@"y"]];
            CLLocationCoordinate2D resultCoor = CLLocationCoordinate2DMake([resultY floatValue], [resultX floatValue]);
            // 给block赋值
            if (_locationBlock) {
                _locationBlock(resultCoor);
            }
            [self getAddressWithCoordinate:resultCoor];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"%@", error);
        }];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@", error);
    }];    
    // 停止定位
    [self.lm stopUpdatingLocation];
}

- (void)getLocationCoordinate:(locationBlock)locaiontBlock
{
    _locationBlock = locaiontBlock;
}

- (void)getLocationCoordinate:(locationBlock)locaiontBlock address:(addressBlock)addressBlock
{
    _locationBlock = locaiontBlock;
    _addressBlock = addressBlock;
}

#pragma mark - base64解密
- (NSString *)base64Decode:(NSString *)str
{
    // 1、加密字符串转二进制数据
    NSData *data = [[NSData alloc] initWithBase64EncodedString:str options:NSDataBase64DecodingIgnoreUnknownCharacters];
    // 2、二进制数据转字符串
    return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}

#pragma mark - 经纬度转地址
- (void)getAddressWithCoordinate:(CLLocationCoordinate2D)coor
{
    if (coor.latitude == 0 || coor.longitude == 0) return;
    
    CLLocation *loca = [[CLLocation alloc] initWithLatitude:coor.latitude longitude:coor.longitude];
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:loca completionHandler:^(NSArray *placemarks, NSError *error) {
        if (placemarks.count == 0 || error) return;
        
        CLPlacemark *pm = [placemarks lastObject];
        if (_addressBlock) {
            _addressBlock(pm.thoroughfare);
        }
    }];
}

@end


IOS8后,请求定位需要请求权限,代码 ZYLocationManager.m已经写好了,不过还需要在info.plist中,添加两个属性NSLocationAlwaysUsageDescription和NSLocationWhenInUseUsageDescription,属性值即是你需要提示给用户的信息,如下图所示:


        将ZYLocationManager.h和ZYLocationManager.m拖入项目中,即可直接调用ZYLocationManager.h定义的两个方法,获取到百度经纬度和地址。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值