使用协议方法实现百度地图的调用
首先导入百度SDK,百度SDK可以手动导入,也可以使用cocoaPods进行导入
创建一个协议方法,
#import <UIKit/UIKit.h>
@protocol IMapView <NSObject>
-(instancetype)initWithFrame:(CGRect)frame;
-(UIView *)getView;
@end
创建对象并继承自IMapView代理
#import <Foundation/Foundation.h>
#import "IMapView.h"
@interface BaiduMapView : NSObject<IMapView>
@end
#import "BaiduMapView.h"
#import <BaiduMapAPI_Map/BMKMapView.h>
@interface BaiduMapView()
@property (nonatomic,strong)BMKMapView *mapView;
@end
@implementation BaiduMapView
-(instancetype)initWithFrame:(CGRect)frame {
self = [super init];
if (self) {
_mapView = [[BMKMapView alloc]initWithFrame:frame];
_mapView.showsUserLocation = YES;
}
return self;
}
-(UIView *)getView {
return _mapView;
}
@end
上面的方法主要是实现百度地图的展示功能
再创建一个协议方法
#import <Foundation/Foundation.h>
#import "IMapView.h"
@protocol IMapFactory <NSObject>
-(id<IMapView>)getMapView:(CGRect)frame;
@end
创建一个对象并继承自IMapFactory
#import <Foundation/Foundation.h>
#import "IMapFactory.h"
@interface BaiduMapFactory : NSObject<IMapFactory>
@end
#import "BaiduMapFactory.h"
#import <BaiduMapKit/BaiduMapAPI_Base/BMKMapManager.h>
#import "BaiduMapView.h"
@interface BaiduMapFactory()
@property (nonatomic,strong)BMKMapManager *mapManager;
@end
@implementation BaiduMapFactory
-(instancetype)init {
self = [super init];
if (self) {
_mapManager = [[BMKMapManager alloc]init];
// 如果要关注网络及授权验证事件,请设定 generalDelegate参数
BOOL ret = [_mapManager start:@"EKwKtqQTUuFEOCdRXGDCjXRAl5vV9M3B" generalDelegate:nil];
if (!ret) {
NSLog(@"manager start failed!");
}
}
return self;
}
- (id<IMapView>)getMapView:(CGRect)frame {
return [[BaiduMapView alloc]initWithFrame:frame];
}
之后再ViewController中实现暂时方法
#import "ViewController.h"
#import "BaiduMapFactory.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
id<IMapFactory> mapFactory = [[BaiduMapFactory alloc]init];
id<IMapView> mapView = [mapFactory getMapView:self.view.frame];
[self.view addSubview:[mapView getView]];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
这样就实现了使用协议完成百度地图集成的方法,是不是很简单
网友评论