簡要

Google Maps 是一個廣泛使用的地圖服務,無論是在應用程式或是網頁上,皆能方便地查詢地點、規劃路線以及獲取公車資訊,甚至能同步電腦與手機上的紀錄。相較於 Apple Maps,Google Maps 在功能上顯得更為完整。本文將介紹如何在 Swift 中使用 Google Maps SDK 來實現位置標記與定位功能。

Google Maps SDK 界面

金鑰申請

使用 Google Maps SDK 前,首先需要申請一組金鑰。請注意,Google Maps API 不是完全免費的,超過一定流量後會收取費用。

Google Maps API 金鑰申請步驟

請訪問以下連結以申請金鑰:
Google API

Step 1 – 點擊開始使用

開始使用 Google Maps API

Step 2 – 點選想使用的功能

選擇功能

Step 3 – 新增專案

新增專案

接下來請持續按下一步。

Step 4 – 取得金鑰

取得金鑰

金鑰非常重要,請妥善保管。

環境安裝

如果你尚未安裝 Cocoapods,請打開 mac 的終端機,切換到你的 iOS 專案資料夾,並執行以下指令:

pod init

這會在資料夾內生成一個 Podfile。請打開該文件,並新增 Google Maps 的 SDK:

pod 'GoogleMaps'
pod 'GooglePlaces'  

儲存文件後,返回終端機並運行以下指令安裝:

pod install

安裝 Google Maps SDK

完成後,請打開新生成的 `.xcworkspace` 檔案。

打開 .xcworkspace 檔案

在 `AppDelegate` 中添加你剛剛申請的金鑰,透過 `GMSServices.provideAPIKey` 方法使所有 class 可以使用 Google Maps SDK。

import UIKit
import GoogleMaps

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    let apiKey = "YOUR_API_KEY" // 替換為你的金鑰
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        GMSServices.provideAPIKey(apiKey)
        return true
    }
}

新增地圖視圖

使用 `GMSMapView` 來新增地圖視圖,以下是示範程式碼:

let mapView = GMSMapView()
mapView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height)
self.view.addSubview(mapView)

設置地圖的相機位置

可以使用 `GMSCameraPosition` 來設定地圖的初始位置,以下是示範程式碼:

let camera = GMSCameraPosition.camera(withLatitude: 25.034012, longitude: 121.564461, zoom: 15.0) // 設定為台北101位置
mapView.camera = camera

設定相機位置

新增標記(大頭針)

使用 `GMSMarker` 來新增標記,並設置標題與副標題:

let marker = GMSMarker()
marker.position = CLLocationCoordinate2DMake(25.034012, 121.563461)
marker.map = mapView
marker.title = "標題1"
marker.snippet = "副標題1"

let marker2 = GMSMarker()
marker2.position = CLLocationCoordinate2DMake(25.034012, 121.566461)
marker2.map = mapView
marker2.title = "標題2"
marker2.snippet = "副標題2"

新增標記

完成!你現在已經成功整合 Google Maps SDK 至你的 Swift 專案。

常見問題解答(Q&A)

Q1: 如何獲取 Google Maps API 金鑰?

A1: 請訪問 [Google Cloud Console](https://console.cloud.google.com/),註冊並創建專案後,按照步驟申請 API 金鑰。

Q2: 如何在 Swift 中使用 Google Maps SDK?

A2: 需要先安裝 Cocoapods,然後在 Podfile 中添加 `pod ‘GoogleMaps’` 和 `pod ‘GooglePlaces’`,接著安裝並在 `AppDelegate` 中提供 API 金鑰。

Q3: Google Maps API 是否收費?

A3: 是的,Google Maps API 提供一定的免費配額,超過後會根據使用量收費,建議查看官方文件了解詳細資訊。

Categorized in: