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

Step by Step:把 Google Map 整合進 Android 應用

編輯:初階開發

Android 與 Google 自家服務的整合向來順手,而地圖大概是最能立刻提升應用價值的一塊。大量 LBS 應用的核心,正是「移動 + 地圖」。以下按步驟說明如何把 Google Map 接進自己的 App。

第一步:安裝 Google Map API

預設安裝 Android SDK 時不含 Maps 函式庫,要做地圖就必須補上。開啟 SDK and AVD Manager,切到 Installed Packages 確認目前安裝內容,若沒有 Maps,再到 Available Packages 中下載安裝。

第二步:取得 debug 憑證

debug.keystore 依平台存放位置不同:

· Windows Vista:C:\Users\<user>\.android\debug.keystore

· Windows XP:C:\Documents and Settings\<user>\.android\debug.keystore

· OS X / Linux:~/.android/debug.keystore

接著用 keytool 產生 MD5 指紋:

%JAVA_HOME%/bin/keytool -list -alias androiddebugkey -keystore debug.keystore \
  -storepass android -keypass android

輸出類似:

androiddebugkey, Apr 2, 2010, PrivateKeyEntry,
Certificate fingerprint (MD5): 72:BF:25:C1:AF:4C:C1:2F:34:D9:B1:90:35:XX:XX:XX

務必留意:正式發布版本必須重新產生一次 MD5 指紋並換新的 API Key。不同 SDK 版本、不同開發機產生的指紋並不相同,換環境後地圖會直接黑屏。

第三步:申請 Map API Key

到 https://code.google.com/android/maps-api-signup.html,把剛才的 MD5 指紋填進去,按下 Generate API Key,即可取得一組可在程式中使用的 Key,頁面上同時會說明用法。

第四步:建立 Map 應用

寫法並不難,只要繼承 MapActivity 即可。MapActivity 主要負責兩件事:管理 Activity 的生命周期,以及為 MapView 建立與釋放相關服務。此外必須實作 isRouteDisplayed(),一般不做路線顯示時回傳 false 就好。

package com.Javacodegeeks.android.googlemaps;

import android.os.Bundle;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;

public class GMapsActivity extends MapActivity {
    private MapView mapView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mapView = (MapView) findViewById(R.id.map_view);
        mapView.setBuiltInZoomControls(true);
    }

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

對應的版面配置:

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

    <com.google.android.maps.MapView
        xmlns:android="https://schemas.android.com/apk/res/android"
        android:id="@+id/map_view"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:clickable="true"
        android:enabled="true"
        android:apiKey="API-KEY-HERE" />
</RelativeLayout>

別忘了把 apiKey 換成第三步申請到的 Key。接著在 AndroidManifest.xml 中補上網路權限,並用 use-library 宣告 Maps 函式庫:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.Javacodegeeks.android.googlemaps"
    android:versionCode="1"
    android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".GMapsActivity" android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <uses-library android:name="com.google.android.maps" />
    </application>
    <uses-permission android:name="android.permission.INTERNET" />
</manifest>

第五步:自訂圖層與標記

要在地圖上打標記,可以繼承 Overlay,但更省事的做法是繼承 ItemizedOverlay<OverlayItem>。它會替我們處理每個 OverlayItem 的繪製、擺放、點擊回應、焦點控制與版面優化。

package com.Javacodegeeks.android.googlemaps;

import java.util.ArrayList;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.drawable.Drawable;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.OverlayItem;

public class CustomItemizedOverlay extends ItemizedOverlay<OverlayItem> {

    private ArrayList<OverlayItem> mapOverlays = new ArrayList<OverlayItem>();
    private Context context;

    public CustomItemizedOverlay(Drawable defaultMarker) {
        super(boundCenterBottom(defaultMarker));
    }

    public CustomItemizedOverlay(Drawable defaultMarker, Context context) {
        this(defaultMarker);
        this.context = context;
    }

    @Override
    protected OverlayItem createItem(int i) {
        return mapOverlays.get(i);
    }

    @Override
    public int size() {
        return mapOverlays.size();
    }

    @Override
    protected boolean onTap(int index) {
        OverlayItem item = mapOverlays.get(index);
        AlertDialog.Builder dialog = new AlertDialog.Builder(context);
        dialog.setTitle(item.getTitle());
        dialog.setMessage(item.getSnippet());
        dialog.show();
        return true;
    }

    public void addOverlay(OverlayItem overlay) {
        mapOverlays.add(overlay);
        this.populate();
    }
}

建構子中的 Drawable 就是標記圖示;ArrayList 保存所有標記;createItem 與 size 分別回傳單一項目與總數;onTap 在使用者點擊標記時觸發,這裡用對話框示意;addOverlay 則把新標記加入並呼叫 populate() 刷新畫面。

使用方式如下:

package com.Javacodegeeks.android.googlemaps;

import java.util.List;
import android.graphics.drawable.Drawable;
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;
import com.google.android.maps.OverlayItem;

public class GMapsActivity extends MapActivity {

    private MapView mapView;
    private static final int latitudeE6 = 37985339;
    private static final int longitudeE6 = 23716735;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mapView = (MapView) findViewById(R.id.map_view);
        mapView.setBuiltInZoomControls(true);

        List<Overlay> mapOverlays = mapView.getOverlays();
        Drawable drawable = this.getResources().getDrawable(R.drawable.icon);
        CustomItemizedOverlay itemizedOverlay =
                new CustomItemizedOverlay(drawable, this);

        GeoPoint point = new GeoPoint(latitudeE6, longitudeE6);
        OverlayItem overlayitem =
                new OverlayItem(point, "Hello", "I'm in Athens, Greece!");
        itemizedOverlay.addOverlay(overlayitem);
        mapOverlays.add(itemizedOverlay);

        MapController mapController = mapView.getController();
        mapController.animateTo(point);
        mapController.setZoom(6);
    }

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

這裡先實例化 CustomItemizedOverlay 並帶入預設圖示,再用經緯度建立 GeoPoint 定位,接著以該座標與一段文字建構 OverlayItem,最後透過 addOverlay 加入圖層。MapController 則負責把視角動畫移動到該座標(animateTo),並用 setZoom 決定縮放層級。

總結

Android 搭配 Google Map 能做的事遠不只顯示座標,GPS 導航、結合社群的位置服務都在射程內。本文只是入門,更多玩法留給讀者自行實作發掘。

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