LoginSignup
8
5

More than 5 years have passed since last update.

Swift3にて、Google Place APIを使って、オートコンプリートを実装してみた。

Posted at

はじめに

やりたいこと

iPhoneアプリで、建物のお店などを検索して取得したい。

やり方

Google Place APIを使って、名前検索してお店を特定。特定したお店の情報を取得。
Guidesの"Add a full-screen control"をやってみました。
ほぼ、デモの通りでした。

Google Place API
https://developers.google.com/places/ios-api/

参考
http://baroqueworksdevjp.blogspot.jp/2016/03/swiftiosgoogle-places-api-for-ios.html

バージョン

Swift 3.02
Xcode 8.2

CocoaPodにて、SDKを取得

pod 'GooglePlaces'
pod install

GooglePlaceのバーションは2.1.1

Podfile.lock
 GooglePlaces (2.1.1):
   GoogleMaps/Base (= 2.1.1)

APIのキーを取得

Google API Consoleに行って、プロジェクトを作成して、
APIキーを取得。

bundle identifierによる制限をかけれるが、とりあえずスキップ。

AIzaSyBdVl-cTICSwYKrZ95SuvNw7dbMuDt1KG0

APIキーをAppDelegate.swiftに追記

まず上部でSDKをimport。

AppDelegate.swift
import GooglePlaces

UIViewController等で、コードを記載

UITextのクリックで、オートコンプリート用のViewが表示され、場所を選択して、選択したものがUITextに表示される。

InputPlaceViewController.swift
// SDKのインポート
import GooglePlaces

class InputPlaceViewController: UIViewController{
    // UITextのoutlet。
    @IBOutlet weak var name: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    // StoryBoardと接続。UITextに入力しようとした時のアクション。
    @IBAction func nameInput(_ sender: UITextField) {
        let autocompleteController = GMSAutocompleteViewController()
        autocompleteController.delegate = self

        // オートコンプリート用のViewの表示
        present(acController, animated: true, completion: nil)
    }
}

// InputPlaceViewControllerを拡張
extension InputPlaceViewController: GMSAutocompleteViewControllerDelegate {

    // オートコンプリートで場所が選択した時に呼ばれる関数
    func viewController(_ viewController: GMSAutocompleteViewController, didAutocompleteWith place: GMSPlace) {
         // 名前をoutletに設定
        name.text = place.name
        print(place)
        print("Place name: \(place.name)")
        print("Place address: \(place.formattedAddress)")
        print("Place attributions: \(place.attributions)")
        dismiss(animated: true, completion: nil)
    }

    func viewController(_ viewController: GMSAutocompleteViewController, didFailAutocompleteWithError error: Error) {
        // TODO: handle the error.
        print("Error: \(error)")
        dismiss(animated: true, completion: nil)
    }

    // User cancelled the operation.
    func wasCancelled(_ viewController: GMSAutocompleteViewController) {
        print("Autocomplete was cancelled.")
        dismiss(animated: true, completion: nil)
    }
}


8
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
5