Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Google Maps Android API v2:用 MapFragment 取代 MapActivity

編輯:Android 開發實例

地圖功能在 Android 上有過幾種做法,各自的限制值得先弄清楚,否則很容易在專案中期才發現路走錯了。

三種做法的限制

MapView + MapActivity:想使用 MapView,Activity 就必須繼承 MapActivity,這會直接吃掉繼承結構,在需要多層繼承時非常綁手。而且官方已明確宣布第一版 API 停止維護:

Version 1 of the Google Maps Android API has been officially deprecated as of December 3rd, 2012. From March 3rd, 2013 you will no longer be able to request an API key for this version. No new features will be added. Apps using v1 will continue to work on devices, but existing and new developers are encouraged to use Google Maps Android API v2.

MapFragment:不再需要繼承 MapActivity,改以 Fragment 方式嵌入,彈性大得多。代價是必須安裝 Google Play Services(實務上意味著需要帶 GMS 的原生 ROM),且需要較新的 SDK 版本。

WebView:把網頁版地圖包進來,理論上最不受限制,但效能與互動體驗都不如前兩者。

以下示範 MapFragment 的整合流程,官方文件在 https://developers.google.com/maps/documentation/android/start。

一、申請 API Key

到 Google API Console 建立專案,開啟 API Access,先在 Services 中啟用「Google Maps Android API v2」,再到 API Access 填入你專案 keystore 的 SHA1 憑證與套件名稱,即可取得專屬的 API key。

二、下載並匯入 Google Play Services

開啟 SDK Manager,在 Extras 中安裝 Android Support Library 與 Google Play Services。相關檔案位於 <sdk>/extras/google/google_play_services/,把其中的 lib_project 匯入作為自己專案的 library 參考。

三、設定 AndroidManifest.xml

<permission
    android:name="com.example.permission.MAPS_RECEIVE"
    android:protectionLevel="signature"/>

<uses-permission android:name="com.example.permission.MAPS_RECEIVE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>

<!-- My Location -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

<!-- Maps API needs OpenGL ES 2.0 -->
<uses-feature
    android:glEsVersion="0x00020000"
    android:required="true"/>

記得把 com.example 換成自己專案的套件名稱。接著在 application 節點內加上 API key:

<meta-data
    android:name="com.google.android.maps.v2.API_KEY"
    android:value="你的 API Key"/>

四、在版面中宣告 MapFragment

<fragment xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    class="com.google.android.gms.maps.MapFragment"/>

Activity 端就單純多了,直接繼承 Activity 即可,不必再綁 MapActivity。

最容易踩到的坑

Debug 簽章看不到地圖。這是初學者最常回報的問題。API key 是綁定 keystore 憑證的,debug 用的預設 keystore 和正式簽名不同,因此一定要用正式簽名打包安裝,地圖才會正常顯示。

另外補充兩點實務經驗:定位權限屬於危險權限,在 Android 6.0 以上必須在執行期動態向使用者申請,光在 manifest 宣告是不夠的;Google Maps API v2 也只能用於有安裝 Google Play Services 的裝置,若目標客群包含中國大陸或無 GMS 的機型,需要另外評估替代方案。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved