您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

在 iOS 專案中整合 Google Maps SDK 的完整步驟

編輯:iOS 相關資訊

一、申請 API Key

要使用 Google Maps SDK for iOS,必須先為你的 App 申請一組 API Key。它的作用除了驗證身分,也能讓你在後台監看 App 對 API 的呼叫量。申請是免費的,取得方式是透過 Google APIs Console 提供你 App 的 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。

若 bundle identifier 與實際 App 不符,地圖會顯示為空白,這是新手最常遇到的狀況,值得先確認。

二、把 SDK 加入專案

Google Maps SDK for iOS 是一個包含資源包的靜態框架(static framework)。

1. 建立一個新專案,勾選使用 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,開啟 Build Phases,在 Link Binary With Libraries 中加入:AVFoundation、CoreData、CoreLocation、CoreText、GLKit、ImageIO、OpenGLES、QuartzCore、SystemConfiguration,以及 libc++.dylib、libicucore.dylib、libz.dylib。

6. 切到 Build Settings,把 Architectures 的預設值改為 armv7;在 Other Linker Flags 加入 -ObjC。若找不到這些欄位,把上方篩選條件改為 All。

7. 最後在 AppDelegate 中帶入 API Key:

#import <GoogleMaps/GoogleMaps.h>

- (BOOL)application:(UIApplication *)application
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [GMSServices provideAPIKey:@"YOUR_API_KEY"];
    return YES;
}

三、加入第一個地圖

- (void)viewDidLoad {
    [super viewDidLoad];

    // 建立相機位置:指定座標與縮放層級
    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_;
}

四、幾個實務提醒

1. 隱私權限。 若需要使用使用者定位(例如顯示藍點),必須在 Info.plist 加上 NSLocationWhenInUseUsageDescription 或 NSLocationAlwaysUsageDescription,並呼叫 mapView_.myLocationEnabled = YES。

2. 不要手動改地圖的 frame。 GMSMapView 會隨父 view 自動調整,直接改 frame 容易造成渲染異常;應改在 Auto Layout 約束或 layoutSubviews 中處理父層尺寸。

3. API Key 保護。 雖然 bundle identifier 已提供一層限制,仍建議透過 bundle ID 白名單與後端代理來降低被盜用的風險,切勿把付費 API 的權杖直接寫死在客戶端。

4. 中國大陸可用性。 若目標使用者主要在中國大陸,需留意 Google 服務的連通性問題;這類專案通常會預留可切換的地圖供應商抽象層,方便替換為其他服務。

5. 版本差異。 本文以早期 Google Maps SDK 為例。目前官方已改用 CocoaPods/Swift Package Manager 整合,並以 GMSServices.provideAPIKey 之外的新版 Map ID 機制管理樣式,建議以官方最新整合文件為準。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved