AndroidでGoogleMapsAPI V2を利用する
AndroidでGoogleMapsを動かすのに苦労したのでメモ
GoogleMapを動かすために必要な定義
Android Studioから自動生成されたので、抜け漏れがあるかも
アプリケーションタグの中に記述します
- 現在地を取得するためのパーミッションを追加
地図の利用に必須ではないとは書いてあったが、今後使うので追加
・ACCESS_COARSE_LOCATION: Wifi経由での現在地取得
・ACCESS_FINE_LOCATION: GPS経由での現在地取得
AndroidManifest.xml
<application ~~> <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="@string/google_maps_key" /> </application> <!-- The ACCESS_COARSE/FINE_LOCATION permissions are not required to use Google Maps Android API v2, but are recommended. --> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
- Google Maps API V2 のAPI KEYを登録
keyの登録はrelease/res/values/google_maps_api.xmlに以下のように書いてあった
<string name="google_maps_key_instructions" templateMergeStrategy="replace"><!-- TODO: Before you run your application, you need a Google Maps API key. To get one, follow this link, follow the directions and press "Create" at the end: https://console.developers.google.com/flows/enableapi?apiid=maps_android_backend&keyType=CLIENT_SIDE_ANDROID&r=~ You can also add your credentials to an existing key, using this line:~ Once you have your key (it starts with "AIza"), replace the "google_maps_key" string in this file. --></string> <string name="google_maps_key" templateMergeStrategy="preserve">YOUR KEY HERE</string>
ちなみに、ここに記載されているSHA1のハッシュ値は、~/.android/debug.keystoreのものらしい
本番にデプロイするときは、アプリケーション単位にキーを発行して使うのが正しいと思われる
発行したキーをgoogle_maps_keyに入れればいいっぽい
起動してみると、以下のエラーがでた
Failed to load map. Error contacting Google servers. This is probably an authentication issue (but could be due to network errors).
APIキーが認識されていないらしい
この辺を参考に
http://iwave-fe.blogspot.jp/2013/09/google-maps-android-api-v2-nexus7.html
これも一応登録してみる
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
それでもうまくいかず
試行錯誤した結果
AndroidManifest.xmlに直書きで通った
<meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="API KEY" />
Android初心者なので、よくわかってないがxmlのvalueが上がかれてない気がする
releaseフォルダにあるから、リリースのときだけxmlが適用されるのかも
うーん。。ここにはこれでいいっぽい感じで書いてあったんだけど。。
http://www.techotopia.com/index.php/Working_with_the_Google_Maps_Android_API_in_Android_Studio
とりあえず、地図は表示された
参考:
http://9ensan.com/blog/smartphone/android/google-maps-android-api-v2-sample/
http://qiita.com/tomo_klotho/items/d2386cb473ed011c9a89