想在 iOS 專案裡嵌入一張中文地圖,百度地圖 SDK 是很常見的選擇。不過它並不是拖進來就能用的 CocoaPods 元件,而是需要手動導入 framework、補齊系統依賴庫、撰寫 Objective-C 橋接頭檔的一整套流程。下面把整個過程拆開來講,最後附上一個可直接跑起來的 Swift 範例。
所有調用都要憑證,所以第一步是到百度地圖開放平台(https://lbsyun.baidu.com/)註冊並建立應用,取得屬於你的 API Key。建立時記得填寫 Bundle Identifier,它和後續的授權校驗直接相關。
從 iOS 9 開始,App Transport Security 預設只允許 HTTPS 連線,而 SDK 內部仍有部分請求走 HTTP。若不做處理,地圖會出現空白或定位失敗。在 Info.plist 中加入以下例外設定:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
這等於對 ATS 開了全閘,屬於妥協做法。若日後 SDK 全面支援 HTTPS,建議改回更精細的域名白名單。
百度地圖以 framework 形式發布,直接從官網下載即可,解壓後會看到多個分包。
BaiduMapAPI_Base.framework 是基礎設施包,任何情況下都必須導入;其餘分包依功能選用。本文只示範地圖顯示,因此再補上 BaiduMapAPI_Map.framework 即可。若之後要做檢索、定位、雲檢索或周邊雷達,再各自加入 Search、Location、Cloud、Radar、Utils 等分包。
SDK 的定位能力依賴 CoreLocation,動畫與渲染走 OpenGL 與 QuartzCore,網路請求與加密又牽涉到 SystemConfiguration 與 Security。進入 Project → Build Phases → Link Binary With Libraries,補齊下列項目:
CoreLocation.framework、QuartzCore.framework、OpenGLES.framework、SystemConfiguration.framework、CoreGraphics.framework、Security.framework、libsqlite3.0.tbd、CoreTelephony.framework、libstdc++.6.0.9.tbd
這個 bundle 裡放的是定位圖示、預設大頭針樣式、路線關鍵點圖示,以及向量地圖渲染必需的資源。少了它,地圖能顯示卻會缺圖。
做法是在工程名稱上右鍵選擇 Add Files to "工程名"...,定位到 BaiduMapAPI_Map.framework → Resources → mapapi.bundle,勾選 Copy items if needed 後加入。
如果你打算全部自繪,也可以把 bundle 內的 image 目錄刪掉或替換成自己的素材,體積能省下不少。
Swift 要調用 Objective-C 的 SDK,得靠 bridging header 把需要的標頭檔匯入。這裡只引入 base 與 map 兩組:
#import <BaiduMapAPI_Base/BMKBaseComponent.h> // base 相關全部標頭 #import <BaiduMapAPI_Map/BMKMapComponent.h> // 地圖功能全部標頭 #import <BaiduMapAPI_Map/BMKMapView.h> // 也可只引入單個標頭 /****** 以下依需求再取消註解 ******/ //#import <BaiduMapAPI_Search/BMKSearchComponent.h> // 檢索 //#import <BaiduMapAPI_Cloud/BMKCloudSearchComponent.h> // 雲檢索 //#import <BaiduMapAPI_Location/BMKLocationComponent.h> // 定位 //#import <BaiduMapAPI_Utils/BMKUtilsComponent.h> // 計算工具 //#import <BaiduMapAPI_Radar/BMKRadarComponent.h> // 周邊雷達
啟動後直接鋪滿一張地圖,中心點設在上海東方明珠一帶,再額外放一個自訂座標的標注作為示範。
BMKMapManager 必須在啟動時就 start,並把先前申請到的 Key 傳進去。若需要監聽網路狀態與授權結果,記得實作 generalDelegate。
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, BMKGeneralDelegate {
var window: UIWindow?
var _mapManager: BMKMapManager?
func application(application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
_mapManager = BMKMapManager()
// 傳入 generalDelegate 以接收網路與授權驗證事件
let ret = _mapManager?.start("mRYTrHzAZUlT5Aojf5tMSxxxxxxxxxxx",
generalDelegate: self)
if ret == false {
NSLog("manager start failed!")
}
return true
}
//...............
}
BMKMapView 就是一個普通的 UIView 子類,用 frame 撐滿整個畫面即可。中心點與顯示範圍在 viewDidAppear 中設定,順便加上一個 BMKPointAnnotation。
import UIKit
class ViewController: UIViewController {
// 百度地圖 View
var _mapView: BMKMapView?
override func viewDidLoad() {
super.viewDidLoad()
// 建立地圖並鋪滿畫面
_mapView = BMKMapView(frame: CGRect(x: 0, y: 0,
width: self.view.frame.width,
height: self.view.frame.height))
self.view.addSubview(_mapView!)
}
override func viewDidAppear(animated: Bool) {
// 地圖中心座標(東方明珠)
let center = CLLocationCoordinate2D(latitude: 31.245087, longitude: 121.506656)
// span 數值越小,視角越近
let span = BMKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05)
let region = BMKCoordinateRegion(center: center, span: span)
_mapView?.region = region
// 加上一個標注
let annotation = BMKPointAnnotation()
var coor = CLLocationCoordinate2D()
coor.latitude = 31.254087
coor.longitude = 121.512656
annotation.coordinate = coor
annotation.title = "這裡有隻野生皮卡丘"
_mapView!.addAnnotation(annotation)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
授權失敗通常不是程式碼問題,而是 Key 與 Bundle ID 不匹配,或是漏了第二步的 ATS 設定。地圖能動但標點全是一片空白,多半是忘了把 mapapi.bundle 加進來。另外別忘了在 AppDelegate 裡啟動 manager,少了這一步 BMKMapView 會一片慘白。