按照本指南中的步骤下载 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 开发,请创建一个 Single View Application。)
- 在您的项目目录中创建一个名为
Podfile的文件。此文件定义您项目的依赖项。 - 编辑
Podfile并添加您的依赖项。以下示例指定了您应用的目标名称以及与 Places API for iOS 一起生成的两个 Pod 的名称(只有在您使用地点选取器示例时才需要GoglePlacePicker和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 及其可能具有的任何依赖项。pod install
关闭 Xcode,然后打开(双击)您的项目的
.xcworkspace文件以启动 Xcode。从此刻开始,您必须使用.xcworkspace文件打开项目。
手动安装
本指南介绍如何向您的项目手动添加 GooglePlaces 框架,以及如何在 Xcode 中配置您的构建设置。
- 下载 SDK 源文件:
只有在您使用地点选取器时才需要 GooglePlacePicker-2.0.1。
- 解压缩源文件。
- 启动 Xcode,并打开现有的项目或创建新项目。如果您刚开始接触 iOS,请创建一个 Single View Application,然后停用 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。 - 从
Resources文件夹将GooglePlaces.bundle拖动到您的项目中。系统提示时,请确保未选中 Copy items into destination group's folder。 - 如果您使用的是地点选取器,请重复上述步骤,并将
GoogleMaps.bundle和GooglePlacePicker.bundle文件拖动到项目中。您可以分别在GoogleMaps.framework和GooglePlacePicker.framework中找到这些文件。 - 从项目导航器中选择您的项目,然后选择您的应用的目标。
- 打开 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。
- 在 Credentials 页面上,获取 API 密钥。
注:如果您已有 iOS 特定的 API 密钥,可以使用该密钥。您可以在同一项目中的任何 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 密钥添加到应用中。
按以下步骤为您的 AppDelegate.swift 添加 API 密钥:
- 添加以下 import 语句:
import GooglePlaces
- 为您的
application(_:didFinishLaunchingWithOptions:)方法添加以下内容,将 YOUR_API_KEY 替换为您的 API 密钥:GMSPlacesClient.provideAPIKey("YOUR_API_KEY")
按以下步骤为您的 AppDelegate.m 添加 API 密钥:
- 添加以下 import 语句:
@import GooglePlaces;
- 为您的
application:didFinishLaunchingWithOptions:方法添加以下内容,将 YOUR_API_KEY 替换为您的 API 密钥:[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