加入含有標記的地圖
本教學課程說明如何在 iOS 應用程式中加入 Google 地圖。地圖中包含一個標記 (也稱為圖釘),用以表示特定位置。
取得程式碼
從 GitHub 複製或下載 Google 地圖 iOS 範例存放區。
設定您的開發專案
請按照下列步驟安裝 Maps SDK for iOS:
- 下載並安裝 Xcode 13.0 以上版本。
- 如果您還沒有 CocoaPods,請在終端機中執行下列指令,以便在 macOS 中安裝這個軟體:
sudo gem install cocoapods
- 複製或下載 Google 地圖 iOS 範例存放區。
- 前往
tutorials/map-with-marker
目錄。 - 執行
pod install
指令。這會安裝在Podfile
中指定的 API 及其可能的依附元件。 - 開啟 (按兩下) 專案的 map-with-Marker.xcworkspace 檔案以 Xcode 開啟檔案。您必須使用
.xcworkspace
檔案才能開啟專案。
取得 API 金鑰並啟用必要的 API
如想完成本教學課程,您必須取得獲授權使用 Maps SDK for iOS 的 Google API 金鑰。點選下方按鈕即可取得金鑰並啟用 API。
開始使用詳情請參閱取得 API 金鑰。
Add the API key to your application
Swift
將 API 金鑰新增到您的 AppDelegate.swift
中,如下所示:
- 請注意,下列匯入陳述式已新增至檔案:
import GoogleMaps
- 在
application(_:didFinishLaunchingWithOptions:)
方法中編輯以下指令列,將 YOUR_API_KEY 替換為您的 API 金鑰:GMSServices.provideAPIKey("YOUR_API_KEY")
Objective-C
將 API 金鑰新增到您的 AppDelegate.m
中,如下所示:
- 請注意,下列匯入陳述式已新增至檔案:
@import GoogleMaps;
- 在
application(_:didFinishLaunchingWithOptions:)
方法中編輯以下指令列,將 YOUR_API_KEY 替換為您的 API 金鑰:[GMSServices provideAPIKey:@"YOUR_API_KEY"];
建立並執行應用程式
- 將 iOS 裝置連接到電腦,或是從 Xcode 配置彈出式選單中選取模擬工具。
- 如果您使用的是裝置,請確認已啟用定位服務。 如果您使用的是模擬工具,請從 [Features] (功能) 選單中選取所需位置。
- 在 Xcode 中,按一下 [Product/Run] (產品/執行) 選單選項 (或播放按鈕圖示),
Xcode 會建構應用程式,然後在裝置或模擬工具上執行應用程式。
您應該會看到一個地圖,上面的標記在澳洲東岸的雪梨為中心,類似本頁的圖片。
疑難排解:
- 如未看到地圖,請檢查您是否已按照上述步驟取得 API 金鑰,並將其加入應用程式。查看 Xcode 的偵錯控制台,以取得關於 API 金鑰的錯誤訊息。
- 如果您已透過 iOS 軟體包 ID 限制 API 金鑰,請編輯金鑰以新增應用程式的軟體包 ID:
com.google.examples.map-with-marker
。 - 確認你的 WiFi 或 GPS 連線狀況良好。
- 使用 Xcode 偵錯工具查看記錄檔並為應用程式偵錯。
瞭解程式碼
- 在
loadView()
中建立地圖,並將其設為檢視畫面。Swift
// Create a GMSCameraPosition that tells the map to display the // coordinate -33.86,151.20 at zoom level 6. let camera = GMSCameraPosition.camera(withLatitude: -33.86, longitude: 151.20, zoom: 6.0) let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera) view = mapView
Objective-C
// Create a GMSCameraPosition that tells the map to display the // coordinate -33.86,151.20 at zoom level 6. GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:-33.86 longitude:151.20 zoom:6.0]; GMSMapView *mapView = [[GMSMapView alloc] initWithFrame: CGRectZero camera:camera]; self.view = mapView;
- 在
loadView()
中為地圖新增標記。Swift
// Creates a marker in the center of the map. let marker = GMSMarker() marker.position = CLLocationCoordinate2D(latitude: -33.86, longitude: 151.20) marker.title = "Sydney" marker.snippet = "Australia" marker.map = mapView
Objective-C
// Creates a marker in the center of the map. GMSMarker *marker = [[GMSMarker alloc] init]; marker.position = CLLocationCoordinate2DMake(-33.86, 151.20); marker.title = @"Sydney"; marker.snippet = @"Australia"; marker.map = mapView;
根據預設,Maps SDK for iOS 會在使用者輕觸標記時顯示資訊視窗的內容。如果您可以接受使用預設行為,就不需要為標記新增點擊事件監聽器。
恭喜!您已經建構了一個能顯示 Google 地圖,且其中會指出特定位置標記的 iOS 應用程式。此外,您也已經學會如何使用 Maps SDK for iOS。