Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android Map 新用法:MapFragment 整合完全指南

編輯:關於 Android 程式設計

要在 App 裡嵌入地圖,Android 提供了幾種不同途徑。本文比較 MapView+MapActivity、MapFragment 與 WebView 三種方案的取捨,並重點示範如何使用新版 Google Maps Android API v2 的 MapFragment。

三種方案的取捨

1、MapView+MapActivity:局限在於必須繼承 MapActivity,否則無法使用 MapView,官方已棄用這套做法。

2、MapFragment:局限在於必須安裝 Google Play Service,也就是需要原生 ROM,且 SDK 要在 API 12 以上。

3、WebView:整合起來看似輕鬆,但需要實際驗證。

官方已於 2012 年底正式棄用 Google Maps Android API v1,並鼓勵開發者改用 v2。下面重點說明 MapFragment(v2)的整合流程。

整合步驟

首先到 Google Console 開啟 API Access 權限取得 API key:建立一個 project,在 Services 中開啟 Google Maps Android API v2,再到 API Access 中填入 keystore 的 SHA1 與包名,取得唯一的 API key。

接著打開 SDK Manager,在 Extras 中安裝 Android Support Library 與 Google Play Services,並把 lib_project 匯入作為自己專案的 library。

配置 Manifest

完成後在 manifest.xml 中加入權限與 API key。

參考程式碼 如下:

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

(com.example 替換成自己 project 的 package)

參考程式碼 如下:

<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 ES2.0.-->
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>

放在 application 聲明裡:

參考程式碼 如下:

<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="appkey"/>

加入 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"/>

重點提醒

使用 MapFragment 後,Activity 只要繼承普通的 Activity 即可,不再需要繼承 MapActivity。特別注意:debug 狀態下無法顯示地圖,一定要在正式簽名(release key)下 map 才會顯示出來。若還有疑問,多參考官方文件即可,那裡介紹得很清楚。

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