要在 iOS 應用中呈現地圖,Google Maps SDK for iOS 是一個功能強大的選擇。以下記錄從申請 API Key 到顯示地圖的完整流程。
使用 Google Maps SDK 前,必須為你的應用申請一個 API Key,它能讓你監控應用對 API 的呼叫情況。API Key 是免費的,可應用於任何呼叫 Map API 的應用。你只需在 Google APIs Console 上提供應用的 bundle identifier 即可取得。
取得步驟:
1. 在 Google APIs Console 建立一個 API 專案;
2. 在專案頁面選取左側 Services 面板,開啟 Google Maps SDK for iOS;
3. 選擇 API Access 面板,點擊 Create new iOS key;
4. 輸入一個或多個 bundle identifier(每行一個);
5. 點擊 Create 建立;
6. 在頁面中找到「Key for iOS apps (with bundle identifiers)」,複製其中的 API Key。
Google Maps SDK for iOS 是一個包含資源包的靜態框架,整合步驟如下:
1. 建立新專案,不要勾選 StoryBoard,務必使用 ARC;
2. 將下載的 GoogleMaps.framework 拖到 Frameworks 資料夾,記得勾選 Copy items into destination group's folder;
3. 右擊已加入的 GoogleMaps.framework,選擇 Show in Finder;
4. 將 Resources 資料夾下的 GoogleMaps.bundle 拖進工程(放到 Frameworks 資料夾下),匯入時不要勾選 Copy;
5. 選中專案與應用的 target;
6. 開啟 Build Phases,在 Link Binary with Libraries 中加入以下 frameworks:AVFoundation、CoreData、CoreLocation、CoreText、GLKit、ImageIO、libc++.dylib、libicucore.dylib、libz.dylib、OpenGLES、QuartzCore、SystemConfiguration;
7. 在 Build Settings 中,把 Architectures 預設值改為 armv7,並在 Other Linker Flags 加入 -ObjC(若看不到選項,可在上方篩選中選 All);
8. 最後把 API Key 加入 AppDelegate。
引入標頭檔:
#import <GoogleMaps/GoogleMaps.h>
並在 didFinishLaunchingWithOptions: 方法中加上:
[GMSServices provideAPIKey:@"YOUR_API_KEY"];
- (void)viewDidLoad
{
[super viewDidLoad];
// 建立一個 GMSCameraPosition,告訴 map 在指定的 zoom level 下顯示指定的點
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:-22.86 longitude:151.20 zoom:6];
mapView_ = [GMSMapView mapWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) camera:camera];
[self.view addSubview:mapView_];
// 在地圖中間做一個標記
GMSMarker *marker = [[GMSMarker alloc] init];
marker.position = CLLocationCoordinate2DMake(-22.86, 151.20);
marker.title = @"Sydney";
marker.snippet = @"Australia";
marker.map = mapView_;
}
完成以上步驟後,就能在应用中嵌入 Google 地圖並自訂標記了。