APIkey申请略过,代码参考官方demo
- AMapUtil.h
定义AMapUtil 接口,reGeocodeAction为外部的实例方法
#import <AMapLocationKit/AMapLocationKit.h>
@interface AMapUtil : NSObject
@property (nonatomic, strong) AMapLocationManager *locationManager;
-(void)reGeocodeAction;
@end
- AMapUtil.m
AMapUtil接口实现,本demo只调用 进行单次带逆地理定位请求
#import <Foundation/Foundation.h>
#import "AMapUtil.h"
#define DefaultLocationTimeout 10
#define DefaultReGeocodeTimeout 5
@interface AMapUtil () <AMapLocationManagerDelegate>
@property (nonatomic, copy) AMapLocatingCompletionBlock completionBlock;
@end
@implementation AMapUtil
#pragma mark - Action Handle
-(void)configLocationManager
{
self.locationManager = [[AMapLocationManager alloc] init];
[self.locationManager setDelegate:self];
//设置期望定位精度
[self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
//设置不允许系统暂停定位
[self.locationManager setPausesLocationUpdatesAutomatically:NO];
//设置允许在后台定位
[self.locationManager setAllowsBackgroundLocationUpdates:YES];
//设置定位超时时间
[self.locationManager setLocationTimeout:DefaultLocationTimeout];
//设置逆地理超时时间
[self.locationManager setReGeocodeTimeout:DefaultReGeocodeTimeout];
}
-(void)cleanUpAction
{
//停止定位
[self.locationManager stopUpdatingLocation];
[self.locationManager setDelegate:nil];
}
-(void)reGeocodeAction
{
[self initCompleteBlock];
[self configLocationManager];
//进行单次带逆地理定位请求
[self.locationManager requestLocationWithReGeocode:YES completionBlock:self.completionBlock];
}
-(void)locAction
{
//进行单次定位请求
[self.locationManager requestLocationWithReGeocode:NO completionBlock:self.completionBlock];
}
#pragma mark - Initialization
-(void)initCompleteBlock
{
self.completionBlock = ^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error)
{
if (error)
{
NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
//如果为定位失败的error,则不进行后续操作
if (error.code == AMapLocationErrorLocateFailed)
{
return;
}
}
//得到定位信息
if (location)
{
NSLog(@"%@",location);
NSLog(@"%@",regeocode);
if (regeocode)
{
NSLog(@"%@ \n %@-%@-%.2fm", regeocode.formattedAddress,regeocode.citycode, regeocode.adcode, location.horizontalAccuracy);
}
else
{
NSLog(@"lat:%f;lon:%f \n accuracy:%.2fm", location.coordinate.latitude, location.coordinate.longitude, location.horizontalAccuracy);
}
}
};
}
#pragma mark - Life Cycle
-(void)dealloc
{
[super dealloc];
[self cleanUpAction];
self.completionBlock = nil;
}
@end
-
项目结构
调用
在AppDelegate.m设置APIKey,申请的APIKey在APIKey.h
-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[AMapServices sharedServices].apiKey = (NSString *)APIKey;
}
在方法中调用
AMapUtil *amapUtil = [[AMapUtil alloc] init];
[amapUtil reGeocodeAction ];