公式サイトはこちらです。
Google Places API for iOS
https://developers.google.com/places/ios-api/?hl=ja
SDKの追加
SDKはCocoaPodで公開されています。Podfileに次の項目を追加します。1 2 3 |
1 | 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が必要です。
1 2 3 4 5 6 | func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { GMSServices.provideAPIKey( "YOUR_API_KEY" ) return true } |
Place Autocompleteの使い方
ViewControllerからGMSAutocompleteViewControllerを起動します。オートコンプレートによるPlaceの選択結果は、GMSAutocompleteViewControllerDelegateで受け取ることができます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | 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 件のコメント:
コメントを投稿