依照本指南中的步驟,下載 Google Places API for iOS,將程式庫及其相依性新增到您的應用程式,並取得免費的 API 金鑰。
每個版本皆提供版本資訊。
步驟 1:取得最新版本的 Xcode
要使用 Google Places API for iOS 建置專案,您需要版本 7.3或更新版本的 Xcode。
步驟 2:安裝 API
使用 Cocoapods
Google Places API for iOS 是以兩個 CocoaPod pod 的方式提供。第一個 pod 是 GooglePlaces,包含不需要地圖的所有地點功能(程式設計 API 和自動完成 UI 小工具),另外,GooglePlacePicker 則是獨立的 pod,其中包含在地圖上搜尋及選取地點的小工具。
CocoaPods 是適用於 Swift 與 Objective-C Cocoa 專案的開放原始碼相依性管理員。如果您還沒有 CocoaPods 工具,請從終端機執行下列指令,以便在 macOS 上加以安裝。如需詳細資料,請參閱 CocoaPods 入門指南。
sudo gem install cocoapods
為 Google Places API for iOS 建立 Podfile,並使用它來安裝 API 與其相依項目:
- 如果您還沒有 Xcode 專案,請立即建立專案並將它儲存到您的本機電腦(如果您是 iOS 開發新手,請建立「單一檢視應用程式」。)
- 在專案目錄中建立名為
Podfile的檔案。此檔案會定義您專案的相依性。 - 編輯
Podfile並新增您的相依項目。以下範例會指定您的應用程式目標名稱,以及 Places API for iOS 隨附的兩個 pod 的名稱(僅當您使用的是地點挑選器範例時,才需要GooglePlacePicker與GoogleMaps):source 'https://github.com/CocoaPods/Specs.git' target 'YOUR_APPLICATION_TARGET_NAME_HERE' do pod 'GooglePlaces' pod 'GooglePlacePicker' pod 'GoogleMaps' end
- 儲存該
Podfile。 開啟終端機並移至包含該
Podfile的目錄:cd <path-to-project>
執行
pod install命令。這將會安裝Podfile中所指定的 API,以及那些 API 可能具有的任何相依性項目。pod install
關閉 Xcode,然後開啟(按兩下)您專案的
.xcworkspace檔案以啟動 Xcode。之後,您必須使用.xcworkspace檔案來開啟該專案。
手動安裝
本指南顯示如何在 Xcode 中手動新增 GooglePlaces 架構到您的專案及設定您的建置設定。
- 下載 SDK 原始檔案:
僅當您使用地點挑選器時,才需要 GooglePlacePicker-2.0.1。
- 將原始檔案解除封裝。
- 啟動 Xcode,並開啟現有專案或建立新專案。如果您是 iOS 新手,請建立「單一檢視應用程式」,並且停用 [Use Storyboards],但要啟用 [Use Automatic Reference Counting]。
- 從您的專案中移除任何先前版本的地圖套件組合。
- 將下列套件組合拖曳到您的專案(出現提示時,請選取 [Copy items if needed]):
GooglePlaces-2.0.1/Frameworks/GooglePlaces.frameworkGoogleMaps-2.0.1/Subspecs/Base/Frameworks/GoogleMapsBase.framework
如果您使用地點挑選器,請將下列套件組合拖曳到您的專案中(除了先前所列的套件組合以外):
GooglePlacePicker-2.0.1/Frameworks/GooglePlacePicker.frameworkGoogleMaps-2.0.1/Subspecs/Maps/Frameworks/GoogleMapsCore.frameworkGoogleMaps-2.0.1/Subspecs/Maps/Frameworks/GoogleMaps.framework
- 在您的專案中,用滑鼠右鍵按一下
GooglePlaces.framework,然後選取 [Show In Finder], - 將
GooglePlaces.bundle從Resources資料夾拖曳到您的專案。當出現提示時,請確認未選取 [Copy items into destination group's folder]。 - 如果您使用地點挑選器,請重複上一個步驟並將
GoogleMaps.bundle和GooglePlacePicker.bundle檔案拖曳到您的專案中。這些分別可在GoogleMaps.framework和GooglePlacePicker.framework中找到。 - 從「Project Navigator」選取您的專案,並選擇應用程式的目標。
- 開啟 [Build Phases] 標籤,並在 [Link Binary with Libraries] 中新增下列架構:
GooglePlaces.frameworkGoogleMapsBase.frameworkGooglePlacePicker.framework(僅限使用地點挑選器時)GoogleMapsCore.framework(僅限使用地點挑選器時)GoogleMaps.framework(僅限使用地點挑選器時)Accelerate.frameworkCoreData.frameworkCoreGraphics.frameworkCoreLocation.frameworkCoreText.frameworkGLKit.frameworkImageIO.frameworklibc++.tbdlibz.tbdOpenGLES.frameworkQuartzCore.frameworkSystemConfiguration.frameworkUIKit.framework
選擇您的專案,而不是選擇特定目標,然後開啟 [Build Settings] 標籤。
- 在 [Other Linker Flags] 區塊中,新增
-ObjC。如果看不見這些設定,請將 [Build Settings] 列的篩選器從 [Basic] 變更為 [All]。
步驟 3:取得 API 金鑰
若要開始使用 Google Places API for iOS,請按一下下方按鈕,它將引導您完成啟用 Google Places API for iOS 的程序並取得 API 金鑰。
取得金鑰或者,您也可以依照這些步驟取得 API 金鑰:
- 前往 Google API Console。
- 建立或選取專案。
- 按一下 [Continue] 以啟用 Google Places API for iOS。
- 在 憑證 頁面上,取得 API 金鑰。
注意:如果您擁有具有 iOS 限制的金鑰,您可以使用該金鑰。您可以將同一金鑰用於同一專案中您的任何 iOS 應用程式。 - 在顯示 API 金鑰的對話方塊中,選擇 [Restrict key] 以設定 API 金鑰上的 iOS 限制。
- 在 [Restrictions] 區塊中,選擇 [iOS apps],然後輸入您應用程式的套件組合識別碼。例如:
com.example.helloplaces。 - 按一下 [Save]。
您的新 iOS 金鑰會出現在您專案的 API 金鑰清單中。API 金鑰是字元字串,類似於:
AIzaSyBdVl-cTICSwYKrZ95SuvNw7dbMuDt1KG0
您也可以在 Google API Console 中查詢現有金鑰。
如需有關使用 Google API Console 的詳細資訊,請參閱 API Console 說明。
步驟 4:將 API 金鑰新增到您的應用程式
下列程式碼範例顯示如何將 API 金鑰新增到應用程式。
將您的 API 金鑰新增到您的 AppDelegate.swift,如下所示:
- 新增下列重要陳述式:
import GooglePlaces
- 新增下列內容到您的
application(_:didFinishLaunchingWithOptions:)方法,使用您的 API 金鑰取代 YOUR_API_KEY:GMSPlacesClient.provideAPIKey("YOUR_API_KEY")
將您的 API 金鑰新增到您的 AppDelegate.m,如下所示:
- 新增下列重要陳述式:
@import GooglePlaces;
- 新增下列內容到您的
application:didFinishLaunchingWithOptions:方法,使用您的 API 金鑰取代 YOUR_API_KEY:[GMSPlacesClient provideAPIKey:@"YOUR_API_KEY"];
步驟 5:開始撰寫程式碼
下列程式碼範例示範如何取得目前地點,以及新增地點挑選器 UI 小工具到您的應用程式。
取得目前地點
Swift
import UIKit
import GooglePlaces
class ViewController: UIViewController {
var placesClient: GMSPlacesClient!
// Add a pair of UILabels in Interface Builder, and connect the outlets to these variables.
@IBOutlet var nameLabel: UILabel!
@IBOutlet var addressLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
placesClient = GMSPlacesClient.shared()
}
// Add a UIButton in Interface Builder, and connect the action to this function.
@IBAction func getCurrentPlace(_ sender: UIButton) {
placesClient.currentPlace(callback: { (placeLikelihoodList, error) -> Void in
if let error = error {
print("Pick Place error: \(error.localizedDescription)")
return
}
self.nameLabel.text = "No current place"
self.addressLabel.text = ""
if let placeLikelihoodList = placeLikelihoodList {
let place = placeLikelihoodList.likelihoods.first?.place
if let place = place {
self.nameLabel.text = place.name
self.addressLabel.text = place.formattedAddress?.components(separatedBy: ", ")
.joined(separator: "\n")
}
}
})
}
}
Objective-C
#import "ViewController.h"
@import GooglePlaces;
@interface ViewController ()
// Add a pair of UILabels in Interface Builder, and connect the outlets to these variables.
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UILabel *addressLabel;
@end
@implementation ViewController {
GMSPlacesClient *_placesClient;
}
- (void)viewDidLoad {
[super viewDidLoad];
_placesClient = [GMSPlacesClient sharedClient];
}
// Add a UIButton in Interface Builder, and connect the action to this function.
- (IBAction)getCurrentPlace:(UIButton *)sender {
[_placesClient currentPlaceWithCallback:^(GMSPlaceLikelihoodList *placeLikelihoodList, NSError *error){
if (error != nil) {
NSLog(@"Pick Place error %@", [error localizedDescription]);
return;
}
self.nameLabel.text = @"No current place";
self.addressLabel.text = @"";
if (placeLikelihoodList != nil) {
GMSPlace *place = [[[placeLikelihoodList likelihoods] firstObject] place];
if (place != nil) {
self.nameLabel.text = place.name;
self.addressLabel.text = [[place.formattedAddress componentsSeparatedByString:@", "]
componentsJoinedByString:@"\n"];
}
}
}];
}
@end
新增地點挑選器
隨著 Google Places API for iOS 提供的 SDK 示範應用程式包括適用於地點挑選器 UI 小工具的範例應用程式。要安裝地點挑選器示範,請使用 pod try GooglePlacePicker 命令。如需更多詳細資料,請參閱程式碼範例指南。
以下是建立地點挑選器的快速介紹範例。
Swift
import UIKit
import GooglePlacePicker
class ViewController: UIViewController {
// Add a pair of UILabels in Interface Builder, and connect the outlets to these variables.
@IBOutlet var nameLabel: UILabel!
@IBOutlet var addressLabel: UILabel!
// Add a UIButton in Interface Builder, and connect the action to this function.
@IBAction func pickPlace(_ sender: UIButton) {
let center = CLLocationCoordinate2D(latitude: 37.788204, longitude: -122.411937)
let northEast = CLLocationCoordinate2D(latitude: center.latitude + 0.001, longitude: center.longitude + 0.001)
let southWest = CLLocationCoordinate2D(latitude: center.latitude - 0.001, longitude: center.longitude - 0.001)
let viewport = GMSCoordinateBounds(coordinate: northEast, coordinate: southWest)
let config = GMSPlacePickerConfig(viewport: viewport)
let placePicker = GMSPlacePicker(config: config)
placePicker.pickPlace(callback: {(place, error) -> Void in
if let error = error {
print("Pick Place error: \(error.localizedDescription)")
return
}
if let place = place {
self.nameLabel.text = place.name
self.addressLabel.text = place.formattedAddress?.components(separatedBy: ", ")
.joined(separator: "\n")
} else {
self.nameLabel.text = "No place selected"
self.addressLabel.text = ""
}
})
}
}
Objective-C
#import "ViewController.h"
@import GooglePlacePicker;
@interface ViewController ()
// Add a pair of UILabels in Interface Builder, and connect the outlets to these variables.
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UILabel *addressLabel;
@end
@implementation ViewController {
GMSPlacePicker *_placePicker;
}
// Add a UIButton in Interface Builder, and connect the action to this function.
- (IBAction)pickPlace:(UIButton *)sender {
CLLocationCoordinate2D center = CLLocationCoordinate2DMake(37.788204, -122.411937);
CLLocationCoordinate2D northEast = CLLocationCoordinate2DMake(center.latitude + 0.001,
center.longitude + 0.001);
CLLocationCoordinate2D southWest = CLLocationCoordinate2DMake(center.latitude - 0.001,
center.longitude - 0.001);
GMSCoordinateBounds *viewport = [[GMSCoordinateBounds alloc] initWithCoordinate:northEast
coordinate:southWest];
GMSPlacePickerConfig *config = [[GMSPlacePickerConfig alloc] initWithViewport:viewport];
_placePicker = [[GMSPlacePicker alloc] initWithConfig:config];
[_placePicker pickPlaceWithCallback:^(GMSPlace *place, NSError *error) {
if (error != nil) {
NSLog(@"Pick Place error %@", [error localizedDescription]);
return;
}
if (place != nil) {
self.nameLabel.text = place.name;
self.addressLabel.text = [[place.formattedAddress
componentsSeparatedByString:@", "] componentsJoinedByString:@"\n"];
} else {
self.nameLabel.text = @"No place selected";
self.addressLabel.text = @"";
}
}];
}
@end