第二步, 加入SDK
AMapFoundationKit.framework 和AMapLocationKit.framework
第三步 权限问题
如何在IOS8上正确定位?
使用IOS地图SDK V2.4.0(含)之后版本的SDK,需在info.plist中追加NSLocationWhenInUseUsageDescription或NSLocationAlwaysUsageDescription字段,以申请相应的权限。
代码封装
DHAMapServiceManager类用来实现定位功能
DHAMapServiceManager.h 导入头文件
//地图定位
#import <AMapLocationKit/AMapLocationKit.h>
/**
* 声明block,传递经纬度、反编码、定位是否成功
*/
typedef void (^LocationPosition)(CLLocation *currentLocation,AMapLocationReGeocode *regeocode,BOOL isLocationSuccess);
@interface DHAMapServiceManager : NSObject
@property (nonatomic,copy) LocationPosition locationBlock; //定位到位置的block
//初始化单例类
+ (instancetype)sharedManager;
//启动定位服务 接收位置block
– (void)startAMapLocation:(LocationPosition)block;
@end
DHAMapServiceManager.m文件
@interface DHAMapServiceManager ()
@property (nonatomic, strong) AMapLocationManager *locationManager;//定位管理类
@end
@implementation DHAMapServiceManager
+ (instancetype)sharedManager{
static DHAMapServiceManager *serviceManager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
serviceManager = [[DHAMapServiceManager alloc] init];
//初始化定位管理类
serviceManager.locationManager = [[AMapLocationManager alloc] init];
[serviceManager.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
// 定位超时时间,最低2s,此处设置为2s
serviceManager.locationManager.locationTimeout =2;
// 逆地理请求超时时间,最低2s,此处设置为2s
serviceManager.locationManager.reGeocodeTimeout = 2;
});
return serviceManager;
}
//开启定位请求
– (void)startAMapLocation:(LocationPosition)block{
// 带逆地理(返回坐标和地址信息)。将下面代码中的 YES 改成 NO ,则不会返回地址信息。
[self.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
//停止定位
[self.locationManager stopUpdatingLocation];
if (error)
{
NSLog(@”locError:{%ld – %@};”, (long)error.code, error.localizedDescription);
if (error.code == AMapLocationErrorLocateFailed)
{
block(nil, nil, NO);
return;
}
}
if (regeocode)
{
//地理位置回调
block(location, regeocode, YES);
}
}];
}
@end
定位使用,代码实现
在AppDelegate.m类中,加入头文件
//地图定位
#import <AMapFoundationKit/AMapFoundationKit.h>
#import “APIKey.h”
#import “DHAMapServiceManager.h”
在- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
//定位功能,配置Key
[self configureAMapServiceAPIKey];
}
– (void)configureAMapServiceAPIKey{
[AMapServices sharedServices].apiKey = (NSString *)APIKey;
}
在使用的地方调用方法
– (void)startLocationRequest{
[[DHAMapServiceManager sharedManager] startAMapLocation:^(CLLocation *currentLocation, AMapLocationReGeocode *regeocode, BOOL isLocationSuccess) {
if(isLocationSuccess) {
NSLog(@”reGeocode:%@”, regeocode);
}else{
NSLog(@”定位失败”);
}
}];
}