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

Android 地圖開發入門:MapView、API Key 與地圖模式切換

編輯:Android 開發實例

Google Maps 提供矢量地圖、衛星影像與地形圖三種視圖,在 Android 上則被拆成兩組能力:負責「畫地圖」的地圖 API,與負責「知道我在哪」的定位 API。兩者搭配,就能做出導航、找店家、標記位置等應用。本文從申請金鑰一路走到一個可切換地圖模式的小程式。

地圖服務能做的事

  • 我的位置:即使沒有 GPS,也能透過附近的無線基地台訊號估算所在位置,精度通常在千米級;若有內建 GPS 或藍牙 GPS 感測器,定位會更準。
  • 地圖與衛星視圖:可沿任一方向捲動,並以快捷鍵縮放,操作手感與桌面版一致。
  • 商戶列表:搭配本地搜尋,可用名稱或類型(例如「咖啡」)查詢店家,查看營業時間與評價,一鍵撥號;有了「我的位置」甚至不必輸入所在地。
  • 駕駛路線:逐段標示轉彎,起點可由目前位置帶入。
  • 大眾運輸:查詢公車與地鐵轉乘路線。
  • 即時路況:以綠、黃、紅三色表示路段暢旺程度。
  • 收藏/書籤:把常去的地點存起來,方便隨時回到同一位置。

一、取得 API Key

傳統(Maps Android API v1)流程是拿 debug keystore 的 MD5 認證指紋去換一組 apiKey:

先開啟 Eclipse 的 Window → Preferences → Android → Build,查到 debug keystore 的位置,接著用 keytool 讀出指紋:

keytool -list -alias androiddebugkey
        -keystore "C:\Users\<你的使用者>\.android\debug.keystore"
        -storepass android -keypass android

輸出中的「認證指紋 (MD5)」就是申請時要填的字串,貼到 Google 的地圖 API 註冊頁後即可取得 apiKey。

這裡必須補上一段重要背景:v1 這套 MD5 指紋換金鑰的做法早已停止服務,目前應使用 Maps SDK for Android,金鑰改由 Google Cloud 主控台建立、綁定到 SHA-1 憑證並設定 API 限制,版面元件也換成 MapFragment/SupportMapFragment。下面的程式碼保留 v1 的寫法作為概念理解,實際開發請對照現行 SDK 文件。

二、把 MapView 放進版面

<com.google.android.maps.MapView
    android:id="@+id/mapview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:apiKey="你的API_KEY" />

等價的 <view> 寫法也可以:

<view android:id="@+id/mv"
    class="com.google.android.maps.MapView"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:apiKey="你的API_KEY" />

三、Manifest:權限與函式庫宣告

<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.package.name">

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />

    <application android:name="MyApplication">
        <uses-library android:name="com.google.android.maps" />
        ...
    </application>
</manifest>

地圖相關的類別並不在標準 Android SDK 裡,而來自 add-on 中的 com.google.android.maps 套件(位於 SDK 的 add-ons/google_apis*/libs 目錄)。因此建立專案時,build target 必須選「Google APIs」而非純 Android 版本。

四、地圖相關類別怎麼分工

  • MapView:顯示地圖的 View,同樣繼承自 ViewGroup,因此能容納其他子元件。可透過 setSatellite()、setTraffic()、setStreetView() 切換顯示模式,setBuiltInZoomControls(true) 則會在地圖上顯示縮放控制(Android 1.5 以後支援)。
  • MapController:由 mapView.getController() 取得,負責視角操作,例如 setCenter()、animateTo()、setZoom()。
  • GeoPoint:座標物件,注意它的經緯度是「乘以 1000000 後的整數」,不是浮點數。
  • MapActivity:抽象類別,任何要顯示 MapView 的 Activity 都必須繼承它,並實作 isRouteDisplayed()。之所以需要專屬的 Activity,是因為 MapView 得靠背景執行緒連網或讀檔,而這些執行緒由 MapActivity 代管。

五、動手做:可切換模式的地圖

目標很明確——顯示地圖、支援縮放、加上選單讓使用者手動切換地圖模式。

Step 1:新增 Android 專案,build target 選擇「Google APIs」。

Step 2:修改 manifest,補上權限與 uses-library:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.map.prac"
    android:versionCode="1"
    android:versionName="1.0">

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <uses-library android:name="com.google.android.maps" />
        <activity android:name=".MapViewPrac2" android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

    <uses-sdk android:minSdkVersion="3" />
</manifest>

Step 3:版面只放一個 MapView,並把 clickable 打開才能接收觸控:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/main"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <com.google.android.maps.MapView
        android:id="@+id/map"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:enabled="true"
        android:clickable="true"
        android:apiKey="你的API_KEY" />
</LinearLayout>

Step 4:撰寫程式碼,處理初始位置、縮放控制與選單:

package com.map.prac;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

public class MapViewPrac2 extends MapActivity {

    private final String TAG = "MapPrac";
    private MapView mapView;
    private MapController mc;

    final private int menuMode = Menu.FIRST;
    final private int menuExit = Menu.FIRST + 1;
    final private int menuCommandList = Menu.FIRST + 2;
    private int chooseItem = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mapView = (MapView) findViewById(R.id.map);
        mc = mapView.getController();

        mapView.setTraffic(true);
        mapView.setSatellite(false);
        mapView.setStreetView(true);

        // GeoPoint 的經緯度需乘以 1000000 轉為整數
        GeoPoint gp = new GeoPoint((int) (39.95 * 1000000),
                                   (int) (116.37 * 1000000));   // 北京
        mc.setCenter(gp);
        // mc.animateTo(gp);  mc.setZoom(12);

        mapView.setBuiltInZoomControls(true);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, menuMode, 0, "Map Mode");
        menu.add(0, menuCommandList, 1, "Command List");
        menu.add(0, menuExit, 2, "Exit");
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch (item.getItemId()) {
            case menuMode:
                Dialog dMode = new AlertDialog.Builder(this)
                    .setTitle(R.string.alert_dialog_single_choice)
                    .setSingleChoiceItems(R.array.select_dialog_items2, chooseItem,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                chooseItem = which;
                            }
                        })
                    .setPositiveButton(R.string.alert_dialog_ok,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                Log.i(TAG, "item = " + chooseItem);
                                switch (chooseItem) {
                                    case 0: mapView.setSatellite(false); break;
                                    case 1: mapView.setSatellite(true);  break;
                                    case 2: mapView.setTraffic(true);    break;
                                    case 3: mapView.setStreetView(true); break;
                                }
                            }
                        })
                    .setNegativeButton(R.string.alert_dialog_cancel,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) { }
                        })
                    .create();
                dMode.show();
                break;

            case menuCommandList:
                Dialog d = new AlertDialog.Builder(this)
                    .setTitle(R.string.select_dialog)
                    .setItems(R.array.select_dialog_items,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                String[] items = getResources()
                                        .getStringArray(R.array.select_dialog_items);
                                Log.i(TAG, "you choose is: " + items[which]);
                            }
                        })
                    .create();
                d.show();
                break;

            case menuExit:
                finish();
                break;
        }
        return super.onMenuItemSelected(featureId, item);
    }

    @Override
    protected boolean isRouteDisplayed() {
        return false;   // 未顯示路線必須回傳 false,否則會收到警示
    }
}

六、幾個容易忽略的細節

  • isRouteDisplayed() 是 MapActivity 的抽象方法,回傳值必須誠實反映畫面上是否畫了路線,這是授權條款的要求,不是可有可無的樣板。
  • GeoPoint 的整數化座標是 v1 的設計;現行 SDK 改用 LatLng 並接受 double,遷移時別忘了換掉。
  • apiKey 與包名、簽章憑證綁在一起,除錯用的 debug 憑證與上架用的 release 憑證需要各自申請。
  • 定位權限同樣要走執行期請求流程,且建議先檢查 LocationManager/FusedLocationProviderClient 是否可用再要求授權。

這篇的重點不在 API 名稱背誦,而在建立一張「地圖 App 需要哪些零件」的地圖:一個顯示用的 View、一個操作視角的 Controller、一個管理生命週期與背景執行緒的 Activity、一組憑證、兩三個權限。理解這個骨架後,換成任何一代地圖 SDK,遷移都只是替換零件而已。

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