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

Android GPS 取得當前經緯度座標的三種做法

編輯:關於 Android 程式設計

App 中常有「把目前位置回報給伺服器」這類需求。實作上大致有三條路:直接用 Android 原生的 LocationManager、用百度地圖 SDK、或用天地圖 API。本文先完整示範第一種,並說明另外兩種的取用方式。

方案一:使用 Android 原生 API

核心元件是 LocationManager。取得經緯度有兩種策略:

  • getLastKnownLocation():直接拿快取中的最後已知位置,瞬間回傳、幾乎不耗電,但可能很舊甚至為空。
  • requestLocationUpdates():註冊監聽,位置變動時透過 LocationListener 回呼。即時性最好,但需要等待首次定位。

實務上通常兩者並用:先試著拿 last known,若為 null 再掛 listener 等待。

MainActivity.java

public class MainActivity extends Activity {

    private static final String TAG = MainActivity.class.getSimpleName();

    private double latitude  = 0.0;
    private double longitude = 0.0;

    private TextView info;
    private LocationManager locationManager;

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

        info = (TextView) findViewById(R.id.tv);
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            getLocation();          // GPS 已開啟,直接取
        } else {
            toggleGPS();            // 嘗試開啟 GPS
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    getLocation();  // 稍等 2 秒後再取,給定位一點時間
                }
            }, 2000);
        }
    }

    /** 透過系統設定 widget 嘗試開啟 GPS */
    private void toggleGPS() {
        Intent gpsIntent = new Intent();
        gpsIntent.setClassName("com.android.settings",
                "com.android.settings.widget.SettingsAppWidgetProvider");
        gpsIntent.addCategory("android.intent.category.ALTERNATIVE");
        gpsIntent.setData(Uri.parse("custom:3"));
        try {
            PendingIntent.getBroadcast(this, 0, gpsIntent, 0).send();
        } catch (CanceledException e) {
            e.printStackTrace();
        }
    }

    private void getLocation() {
        Location location =
                locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

        if (location != null) {
            latitude  = location.getLatitude();
            longitude = location.getLongitude();
        } else {
            // 沒有快取位置,改為註冊監聽等待更新
            locationManager.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER, 1000, 0, locationListener);
        }

        info.setText("緯度:" + latitude + "\n" + "經度:" + longitude);
    }

    private final LocationListener locationListener = new LocationListener() {

        // Provider 在「可用/暫時不可用/無服務」之間切換時觸發
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) { }

        // Provider 被啟用時觸發,例如 GPS 被打開
        @Override
        public void onProviderEnabled(String provider) {
            Log.e(TAG, provider);
        }

        // Provider 被停用時觸發,例如 GPS 被關閉
        @Override
        public void onProviderDisabled(String provider) {
            Log.e(TAG, provider);
        }

        // 座標改變時觸發;若傳進的是相同座標則不會觸發
        @Override
        public void onLocationChanged(Location location) {
            if (location != null) {
                Log.e("Map", "Location changed : Lat: " + location.getLatitude()
                             + " Lng: " + location.getLongitude());
                latitude  = location.getLatitude();
                longitude = location.getLongitude();
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 別忘了解除註冊,否則會造成記憶體洩漏與電量浪費
        if (locationManager != null && locationListener != null) {
            locationManager.removeUpdates(locationListener);
        }
    }
}

main.xml

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="經緯度信息:"
        android:textColor="#660000"
        android:textSize="20sp" />
</LinearLayout>

AndroidManifest.xml

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

    <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="18" />

    <!-- 網路連線 -->
    <uses-permission android:name="android.permission.INTERNET" />
    <!-- 定位權限:粗定位(基地台/WiFi)與精定位(GPS) -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

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

執行結果:

方案二:百度地圖 API

使用 LocationClient 搭配 Bd09ll 座標型別,另外需要在百度開發者平台申請 API Key 並加入 ak 的 meta-data。優點是國內定位精度與覆蓋率較好,且能直接拿到地址描述;缺點是引入 SDK 體積、依賴第三方服務。

方案三:天地圖 API

同樣需要申請金鑰,座標系統為 CGCS2000。適合需要與其他天地圖服務(電子地圖、影像圖)整合的專案。

選型建議與新版系統注意事項

座標系統是最大陷阱。GPS 給的是 WGS-84,百度用 BD-09,高德/Google 用 GCJ-02,天地圖用 CGCS2000。混用會導致幾十到幾百公尺的偏移。回報給伺服器前,務必確認雙方約定的是同一套座標系。

原生 API 在新版 Android 上的變化:

  • Android 6.0 起定位權限屬危險權限,必須執行期動態申請,只在 Manifest 宣告會直接拿不到位置。
  • 本文的 toggleGPS() 依賴系統設定 App 的内部 widget,在新版系統上基本已失效;正確做法是跳轉 Settings.ACTION_LOCATION_SOURCE_SETTINGS 讓使用者自行開啟。
  • Android 8.0 起背景定位受限,長時間追蹤需改用 Foreground Service 搭配通知。
  • Android 10 起還需區分 ACCESS_BACKGROUND_LOCATION,並引入精確度(fine/coarse)選項。
  • 新專案建議直接採用 Google Play Services 的 FusedLocationProviderClient,它會自動整合 GPS、WiFi、基地台並處理省電策略,比裸用 LocationManager 好用許多。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved