公式サイトはこちらです。
Google Places API for iOS
https://developers.google.com/places/ios-api/?hl=ja
SDKの追加
SDKはCocoaPodで公開されています。Podfileに次の項目を追加します。source 'https://github.com/CocoaPods/Specs.git' platform :ios, '8.1' pod 'GoogleMaps'Podfileに追加の上、installを実行するだけで完了です。
pod install
API Keyの取得
Google Developer Consoleにて、APIの設定が必要です。次はAPI Keyを取得するまでの手順です。- プロジェクトを作成
- Google Places API for iOS と Google Maps SDK for iOSを有効にする
- 認証情報からiOSキーを作成(BundleIDの登録が必要です)
- API Keyを取得する
API Keyのセット
AppDelegate.swiftで、GMSServicesクラスにAPI Keyのセットします。import GoogleMapsが必要です。
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
GMSServices.provideAPIKey("YOUR_API_KEY")
return true
}
Place Autocompleteの使い方
ViewControllerからGMSAutocompleteViewControllerを起動します。オートコンプレートによるPlaceの選択結果は、GMSAutocompleteViewControllerDelegateで受け取ることができます。
extension ViewController: GMSAutocompleteViewControllerDelegate {
func startGooglePlacesAutocomplete(){
let autocompleteController = GMSAutocompleteViewController()
autocompleteController.delegate = self
self.presentViewController(autocompleteController, animated: true, completion: nil)
}
// Handle the user's selection.
func viewController(viewController: GMSAutocompleteViewController, didAutocompleteWithPlace place: GMSPlace) {
print("Place name: ", place.name)
print("Place address: ", place.formattedAddress)
print("Place attributions: ", place.attributions)
self.dismissViewControllerAnimated(true, completion: nil)
}
func viewController(viewController: GMSAutocompleteViewController, didFailAutocompleteWithError error: NSError) {
// TODO: handle the error.
print("Error: ", error.description)
}
// User canceled the operation.
func wasCancelled(viewController: GMSAutocompleteViewController) {
self.dismissViewControllerAnimated(true, completion: nil)
}
// Turn the network activity indicator on and off again.
func didRequestAutocompletePredictions(viewController: GMSAutocompleteViewController) {
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
}
func didUpdateAutocompletePredictions(viewController: GMSAutocompleteViewController) {
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
}
}
GMSAutocompleteViewControllerの起動が成功すると、次のような画面が表示されます。Placesの確定時にdidAutocompleteWithPlaceがコールされるので、引数:placeで値を受け取ります。

0 件のコメント:
コメントを投稿