Google Places API を使ってみる
Google Places APIとは
引用
Google Places API を使えば、Google マップや Google+ と同じデータベースから取得される約 1 億か所の多彩なプレイスの詳細情報にアプリでアクセスできるようになります。
準備
APIキーの取得
https://developers.google.com/places/android-api/?authuser=2
上記のURLにアクセスする
画像にある右上のボタンを押す
新規プロジェクト名を入力し、「Create and enable API」を押す
画像のようにAPIキーが表示されるので、コピーしておく
Androidプロジェクトの設定
AndroidManifest.xmlに以下の記述を追加する
<meta-data android:name="com.google.android.geo.API_KEY" android:value="YOUR_API_KEY"/>
YOUR_API_KEYには先ほど取得したAPIキーが入る
PlacePickerで検索した結果を受け取る
PlacePickerの起動
public void onPickButtonClick(View v) { // Construct an intent for the place picker try { PlacePicker.IntentBuilder intentBuilder = new PlacePicker.IntentBuilder(); Intent intent = intentBuilder.build(this); // Start the intent by requesting a result, // identified by a request code. startActivityForResult(intent, REQUEST_PLACE_PICKER); } catch (GooglePlayServicesRepairableException e) { // ... } catch (GooglePlayServicesNotAvailableException e) { // ... } finally { } }
上記をボタンクリック時に呼び出すことで、PlacePickerを起動できる
PlacePickerが起動しない場合
LOGCATを確認してみて以下のようなログが出ている場合、APIキーの設定が間違っていたり、GooglePlacesAPIが有効でない可能性がある
そのときは、設定を見直してみよう
05-07 17:19:22.699 24288-24415/? E/Volley: [92644] BasicNetwork.performRequest: Unexpected response code 403 for https://www.googleapis.com/placesandroid/v1/placePicker 05-07 17:19:22.702 24288-9756/? E/Places: Invalid API key. Check that <meta-data android:name="com.google.android.geo.API_KEY" android:value="your API key"/> is in the <application> element of AndroidManifest.xml. See https://developers.google.com/places/android/start#api-key for more details. 05-07 17:19:22.702 24288-9756/? E/AsyncOperation: serviceID=65, operation=PlacePickerQuota OperationException[Status{statusCode=PLACES_API_KEY_INVALID, resolution=null}] at amsa.b(:com.google.android.gms:268) at amrz.a(:com.google.android.gms:62) at lin.run(:com.google.android.gms:111) at llt.run(:com.google.android.gms:450) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607) at lqc.run(:com.google.android.gms:17) at java.lang.Thread.run(Thread.java:761) 05-07 17:19:22.715 14797-14797/? E/Places: Place Picker closing due to PLACES_API_KEY_INVALID
選択したPlace情報を受け取る
Place情報はonActivityResultにて受け取る
protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_PLACE_PICKER) { if (resultCode == RESULT_OK) { Place place = PlacePicker.getPlace(this, data); String name = String.format("name: %s\n", place.getName()); Toast.makeText(this, name, Toast.LENGTH_LONG).show(); } } }
Placeクラスから取得できる情報は以下を参照する https://developers.google.com/android/reference/com/google/android/gms/location/places/Place