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

高德地圖 Android 進階開發(三):GPS 定位完整實作

編輯:關於 Android 程式設計

在上一篇把地圖顯示出來之後,下一步自然是「我在哪裡」。高德定位 SDK 把 GPS、Wi-Fi、基站等多種來源封裝成一致的 API,你只要實作幾個回呼,就能拿到經緯度並在地圖上顯示藍點。本文以官方範例為基礎,逐段加上註解,讓整個流程更容易讀懂。

一、先準備權限與服務宣告

定位涉及網路、儲存、電話狀態、Wi-Fi 狀態等多項能力,因此 AndroidManifest.xml 需要一次把權限補齊。另外有一個關鍵點常被忽略:必須宣告 com.amap.api.location.APSService,否則定位會直接失敗並回報錯誤碼 10。

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

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />

    <application>
        <!-- 請替換為自己在高德平台申請的 Key -->
        <meta-data
            android:name="com.amap.api.v2.apikey"
            android:value="你的apikey" />

        <activity android:name=".Main">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <!-- 定位服務,缺少這一段會導致定位失敗 -->
        <service android:name="com.amap.api.location.APSService" />
    </application>
</manifest>

提醒兩點:meta-data 中的 value 一定要換成你自己申請的 Key,直接照抄別人的沒有用;另外若在 Activity 上加上 android:configChanges="orientation|keyboardHidden|screenSize",可以自行處理橫豎屏切換而不重建 Activity。

二、版面配置

版面很單純:一個填滿父容器的 MapView,加上一組 RadioButton 用來切換定位模式,再放一個 TextView 顯示錯誤資訊。

<FrameLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.amap.api.maps.MapView
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <TextView
        android:id="@+id/location_errInfo_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|left"
        android:layout_marginBottom="10dp"
        android:layout_marginLeft="10dp"
        android:visibility="gone" />

    <RadioGroup
        android:id="@+id/gps_radio_group"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="top|left"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="10dp"
        android:orientation="horizontal">

        <RadioButton
            android:id="@+id/gps_locate_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            android:text="@string/gpslocate" />

        <RadioButton
            android:id="@+id/gps_follow_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/gpsfollow" />

        <RadioButton
            android:id="@+id/gps_rotate_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/gpsrotate" />
    </RadioGroup>
</FrameLayout>

三、MainActivity 的實作

這裡的關鍵是讓 Activity 同時實作 LocationSource(提供定位啟動/停止的入口)與 AMapLocationListener(接收定位結果)。地圖只負責顯示,定位由 AMapLocationClient 負責,兩者透過 LocationSource 串接起來。

package com.dragon.arnav;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;

public class Main extends Activity
        implements LocationSource, AMapLocationListener,
        RadioGroup.OnCheckedChangeListener {

    private AMap aMap;
    private MapView mapView;
    private OnLocationChangedListener mListener;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;
    private RadioGroup mGPSModeGroup;
    private TextView mLocationErrText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);

        mapView = (MapView) findViewById(R.id.map);
        mapView.onCreate(savedInstanceState);   // 必須呼叫
        init();
    }

    private void init() {
        if (aMap == null) {
            aMap = mapView.getMap();
            setUpMap();
        }
        mGPSModeGroup = (RadioGroup) findViewById(R.id.gps_radio_group);
        mGPSModeGroup.setOnCheckedChangeListener(this);
        mLocationErrText = (TextView) findViewById(R.id.location_errInfo_text);
        mLocationErrText.setVisibility(View.GONE);
    }

    /** 設定地圖與定位相關屬性 */
    private void setUpMap() {
        aMap.setLocationSource(this);                            // 設定定位來源
        aMap.getUiSettings().setMyLocationButtonEnabled(true);   // 顯示定位按鈕
        aMap.setMyLocationEnabled(true);                         // 顯示定位層並可觸發定位
        aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);       // 定位模式
    }

    /** 切換定位模式:定位 / 跟隨 / 依地圖朝向旋轉 */
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.gps_locate_button:
                aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
                break;
            case R.id.gps_follow_button:
                aMap.setMyLocationType(AMap.LOCATION_TYPE_MAP_FOLLOW);
                break;
            case R.id.gps_rotate_button:
                aMap.setMyLocationType(AMap.LOCATION_TYPE_MAP_ROTATE);
                break;
        }
    }

    /** 激活定位:由地圖在顯示定位層時呼叫 */
    @Override
    public void activate(OnLocationChangedListener listener) {
        mListener = listener;
        if (mlocationClient == null) {
            mlocationClient = new AMapLocationClient(this);
            mLocationOption = new AMapLocationClientOption();
            mlocationClient.setLocationListener(this);
            // 高精度模式,也可改為 Battery_Saving 或 Device_Sensors
            mLocationOption.setLocationMode(
                    AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            mlocationClient.setLocationOption(mLocationOption);
            // 週期定位,最小間隔 2000ms;不需要時請 stopLocation() 以節電
            mlocationClient.startLocation();
        }
    }

    /** 停止定位 */
    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }

    /** 定位結果回呼 */
    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (mListener != null && amapLocation != null) {
            if (amapLocation.getErrorCode() == 0) {
                mLocationErrText.setVisibility(View.GONE);
                mListener.onLocationChanged(amapLocation);  // 地圖顯示藍點
            } else {
                String errText = "定位失敗, " + amapLocation.getErrorCode()
                        + ": " + amapLocation.getErrorInfo();
                Log.e("AmapErr", errText);
                mLocationErrText.setVisibility(View.VISIBLE);
                mLocationErrText.setText(errText);
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
        deactivate();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        if (mlocationClient != null) {
            mlocationClient.onDestroy();
        }
    }
}

四、幾個實務上的注意事項

  • MapView 的生命周期方法(onCreate / onResume / onPause / onSaveInstanceState / onDestroy)必須對應轉發,漏掉任何一個都可能導致地圖空白或記憶體洩漏。
  • 定位模式有三種:LOCATION_TYPE_LOCATE 每次定位地圖都會移動到新位置;LOCATION_TYPE_MAP_FOLLOW 不移動地圖;LOCATION_TYPE_MAP_ROTATE 會依設備朝向旋轉地圖。
  • 週期定位請務必設定合理間隔( SDK 最小支援 2000ms),並在 onPause() 或不需要時呼叫 stopLocation(),這對電量與流量都有明顯影響。
  • strings.xml、colors.xml 這類資源檔這裡不重複列出,直接沿用專案既有的通用寫法即可。

五、成果

執行後可以看到地圖上的藍點隨著位置移動,也能透過上方三個選項切換定位、跟隨與旋轉模式。定位成功後,你就能拿到完整的 AMapLocation 物件,裡面的經緯度、精度、地址等資訊可以進一步做周邊搜尋、導航或地理圍欄等進階應用。

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