iOS開發 -- 百度地圖api的使用
阿新 • • 發佈:2019-01-23
下載百度iOS地圖SDK
下載framework形式靜態庫
申請金鑰 申請步驟上面連結有詳細解釋
獲取金鑰
然後配置開發環境
注意:一般配置的framework所支援的架構同時支援真機和模擬器使用,
然後把xcode裡的檔案一個.m檔案改為.mm檔案 以AppDelegate.m為例
然後在xcode工程裡面匯入 mapapi.bundle檔案以及系統.framework檔案
然後在AppDelegate.m檔案裡 寫如下程式碼
#import "AppDelegate.h"
#import <BaiduMapAPI/BMapKit.h> //引入所有的標頭檔案
//#import <BaiduMapAPI/BMKMapView.h> //只引入所需的單個頭檔案
@interface AppDelegate ()<BMKGeneralDelegate>
@end
BMKMapManager* _mapManager;
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// 要使用百度地圖,請先啟動BaiduMapManager
_mapManager = [[BMKMapManager alloc]init];
BOOL ret = [_mapManager start:@"wLWgKV8elQKI0OtHRGFgf2so" generalDelegate:self];
if (!ret) {
NSLog(@"manager start failed!");
}
return YES;
}
然後在控制器裡.h檔案寫
注意:在使用SDK的類引入標頭檔案:
#import <BaiduMapAPI/BMapKit.h>//引入所有的標頭檔案
#import <BaiduMapAPI/BMKMapView.h> //只引入所需的單個頭檔案
#import <UIKit/UIKit.h>
#import <BaiduMapAPI/BMapKit.h>
@interface ViewController : UIViewController<BMKMapViewDelegate,BMKLocationServiceDelegate>
{
//_mapView是自定義的一個UIView控制元件
__weak IBOutlet BMKMapView *_mapView;
BMKLocationService* _locService;
}
@end
在控制器裡.m檔案寫
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
//緯度40.030401 經度116.343569
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
_locService = [[BMKLocationService alloc]init];
[_locService startUserLocationService];
_mapView.showsUserLocation = NO;//先關閉顯示的定點陣圖層
_mapView.userTrackingMode = BMKUserTrackingModeFollow;//設定定位的狀態
_mapView.showsUserLocation = YES;//顯示定點陣圖層
}
-(void)viewWillAppear:(BOOL)animated {
[_mapView viewWillAppear];
_mapView.delegate = self; // 此處記得不用的時候需要置nil,否則影響記憶體的釋放
_locService.delegate = self;
}
-(void)viewWillDisappear:(BOOL)animated {
[_mapView viewWillDisappear];
_mapView.delegate = nil; // 不用時,置nil
_locService.delegate = nil;
}
/**
*在地圖View將要啟動定位時,會呼叫此函式
*@param mapView 地圖View
*/
- (void)willStartLocatingUser
{
NSLog(@"start locate");
}
/**
*使用者方向更新後,會呼叫此函式
*@param userLocation 新的使用者位置
*/
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
[_mapView updateLocationData:userLocation];
NSLog(@"heading is %@",userLocation.heading);
}
/**
*使用者位置更新後,會呼叫此函式
*@param userLocation 新的使用者位置
*/
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
// NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
[_mapView updateLocationData:userLocation];
}
/**
*定位失敗後,會呼叫此函式
*@param mapView 地圖View
*@param error 錯誤號,參考CLError.h中定義的錯誤號
*/
- (void)didFailToLocateUserWithError:(NSError *)error
{
NSLog(@"location error");
}