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

Android 手機地圖開發全流程:從申請 API Key 到打上標記

編輯:關於 Android 程式設計

手機地圖顯示是位置服務類應用的基礎能力。以下依序說明申請 API 金鑰、掌握核心類別、到最後把自訂標記畫到地圖上的完整流程。

一、申請 Android 地圖 API 金鑰

先取得 debug 憑證的 MD5 指紋:

keytool -list -keystore ~/.android/debug.keystore

把得到的 MD5 碼貼到 https://code.google.com/android/maps-api-signup.html 註冊,完成後會拿到一組金鑰,以及對應的 XML 片段範例:

<com.google.android.maps.MapView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:apiKey="你的API金鑰" />

這組金鑰會綁定到該憑證指紋,也就是說用不同電腦或不同 keystore 編出的 APK 無法共用同一組金鑰——這是換開發機後地圖突然變成空白格最常見的原因。

二、Google Map API 的核心類別

Android 定義了 com.google.android.maps 套件,其中最重要的幾個類別如下:

MapActivity

用於顯示地圖的 Activity 基底類別,需要連線到底層網路。它是抽象類別,任何要顯示 MapView 的 Activity 都必須繼承它,並在 onCreate() 中建立 MapView 實例,同時實作 isRouteDisplay()。

MapView

顯示地圖的 View 元件,繼承自 android.view.ViewGroup。它必須與 MapActivity 搭配使用,且只能由 MapActivity 建立——因為 MapView 需要透過背景執行緒連線網路或檔案系統,而這些執行緒由 MapActivity 管理。

MapController

控制地圖的移動與縮放。

Overlay

可繪製於地圖之上的覆蓋層物件,用來放標記、圖示、文字。

GeoPoint

經緯度座標物件,注意其經緯度必須是 int,且需乘以 1000000 以保留小數精度。

三、實作步驟

1. 建立專案

建立專案時,SDK 目標要選 Google APIs,而非一般 Android 版本,否則找不到 maps 套件。

2. 修改 AndroidManifest.xml

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

    <uses-library android:name="com.google.android.maps" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-sdk android:minSdkVersion="5" />

    <application ...>
        ...
    </application>
</manifest>

<uses-library> 是必须的,少了它會在執行期丟出 ClassNotFoundException;INTERNET 權限則是因為要從網路抓地圖磚。

3. 建立 MapView

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

    <com.google.android.maps.MapView
        android:id="@+id/MapView01"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:apiKey="你的API金鑰" />

</RelativeLayout>

也可以在程式碼中動態建立:

MapView map = new MapView(this, "(android maps api key)");

4. 實作 MapActivity 並設定顯示模式

MapView 提供三種地圖模式:

mMapView.setTraffic(true);     // 交通模式
mMapView.setSatellite(true);   // 衛星模式
mMapView.setStreetView(false); // 街景模式

是否允許縮放則透過:

mMapView.setBuiltInZoomControls(true);

5. 用 MapController 定位與縮放

mMapController = mMapView.getController();

// 設定起點為成都(經緯度需乘以 1000000)
mGeoPoint = new GeoPoint((int) (30.659259 * 1000000),
                         (int) (104.065762 * 1000000));

mMapController.animateTo(mGeoPoint);   // 動畫移動到該點
mMapController.setZoom(15);            // 設定縮放倍率(1~21)

6. 用 Overlay 畫上標記

要在地圖上標註圖示或文字,必須先把經緯度換算成螢幕座標。Map API 提供了 Projection.toPixels(GeoPoint in, Point out) 來做這件事。

首先繼承 Overlay 並實作 draw():

class MyLocationOverlay extends Overlay {
    @Override
    public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) {
        ...
    }
}

完整程式碼

package com.yarin.android.Examples_09_03;

import java.util.List;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.os.Bundle;

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 com.google.android.maps.Overlay;

public class Activity01 extends MapActivity {

    private MapView mMapView;
    private MapController mMapController;
    private GeoPoint mGeoPoint;

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

        mMapView = (MapView) findViewById(R.id.MapView01);

        // mMapView.setTraffic(true);     // 交通模式
        // mMapView.setSatellite(true);   // 衛星模式
        mMapView.setStreetView(false);   // 街景模式

        mMapController = mMapView.getController();
        mMapView.setEnabled(true);
        mMapView.setClickable(true);
        mMapView.setBuiltInZoomControls(true);   // 啟用縮放

        // 定位到成都
        mGeoPoint = new GeoPoint((int) (30.659259 * 1000000),
                                 (int) (104.065762 * 1000000));
        mMapController.animateTo(mGeoPoint);
        mMapController.setZoom(15);

        // 加上自訂 Overlay 顯示標記
        MyLocationOverlay myLocationOverlay = new MyLocationOverlay();
        List<Overlay> list = mMapView.getOverlays();
        list.add(myLocationOverlay);
    }

    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }

    class MyLocationOverlay extends Overlay {
        @Override
        public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) {
            super.draw(canvas, mapView, shadow);

            Paint paint = new Paint();
            Point myScreenCoords = new Point();

            // 把經緯度換算成實際螢幕座標
            mapView.getProjection().toPixels(mGeoPoint, myScreenCoords);

            paint.setStrokeWidth(1);
            paint.setARGB(255, 255, 0, 0);
            paint.setStyle(Paint.Style.STROKE);

            Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.home);
            canvas.drawBitmap(bmp, myScreenCoords.x, myScreenCoords.y, paint);
            canvas.drawText("天府廣場", myScreenCoords.x, myScreenCoords.y, paint);

            return true;
        }
    }
}

實務提醒

本文示範的是已停止維護的 com.google.android.maps(Google Maps Android API v1)。這個 API 早已不核發新金鑰,新專案請改用 Maps SDK for Android(v2 之後),架構差異相當大:

  • 不再需要繼承 MapActivity,改用 SupportMapFragment 或 MapFragment。
  • 金鑰改為在 Manifest 的 <meta-data> 中宣告,且需先在 Google Cloud Console 啟用 Maps SDK。
  • 標記改用 Marker + MarkerOptions,不再需要自己寫 Overlay 換算座標。
  • 定位改用 FusedLocationProviderClient。

若你維護的是舊專案,上面的內容仍然適用;若是全新開發,建議直接以 v2 的架構為起點,能省下大量重寫成本。

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