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

Android 定位實作(015)—— 取得經緯度與地名

編輯:關於 Android 程式設計

在上一篇的基礎上,這次我們把「座標」進一步轉換成「人類看得懂的地名」。也就是說,除了拿到經緯度,還要能告訴使用者「你現在在哪裡附近」。這一節示範兩個關鍵片段:地理編碼反查,以及一個可重複使用的 GPS 定位類別。

從座標反查地址

當我們手上有一組 GeoPoint 時,可以透過 Geocoder 的 getFromLocation 做反向地理編碼,把緯度、經度換成 Address 清單,再從中取出行政區、街道與地標等資訊:

public void getAndRefreshLocation(GeoPoint p) {
    try {
        double lat = (double) p.getLatitudeE6() / 1000000;
        double lon = (double) p.getLongitudeE6() / 1000000;
        List<Address> address = mGeocoder.getFromLocation(lat, lon, 3);
        if (address != null) {
            Address addr = address.get(0);
            String addressName = addr.getAdminArea()
                    + addr.getSubLocality() + addr.getFeatureName()
                    + "附近";
            Toast.makeText(mContext, addressName, Toast.LENGTH_LONG).show();
        }
    } catch (Exception e) {
        LogUtil.i("ReviewPositionUI", e.getMessage());
    }
}

這裡有個常被忽略的細節:GeoPoint 的經緯度是以「度 × 10⁶」的形式儲存(E6 格式),所以要記得除以 1000000 還原成一般座標,再交給地理編碼器使用。

封裝一個 GPSLocation 類別

為了讓定位邏輯可以在各處重複使用,我們把它包成一個獨立的類別,內部同時管理 Google 的 LocationManager 與 LocationManagerProxy:

public class GPSLocation {

    private LocationManagerProxy mLocationManager;
    private Context mContext;
    LocationManager mManager;

    public GPSLocation(Context context) {
        this.mContext = context;
        mLocationManager = LocationManagerProxy.getInstance(context);
        mManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
    }

    public void enableMyLocation(LocationListener listener) {
        Location location;
        if (NetworkState.TYPE_WIFI == NetworkState.searchNetworkType(mContext)) {
            location = mManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        } else {
            location = mManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        }
        if (location != null) {
            listener.onLocationChanged(location);
        } else {
            Criteria cri = new Criteria();
            cri.setAccuracy(Criteria.ACCURACY_COARSE);
            cri.setAltitudeRequired(false);
            cri.setBearingRequired(false);
            cri.setCostAllowed(false);
            String bestProvider = mLocationManager.getBestProvider(cri, true);
            try {
                mLocationManager.requestLocationUpdates(bestProvider, 2000, 10, listener);
            } catch (Exception e) {
                listener.onLocationChanged(null);
            }
        }
    }

    public void disableMyLocation(LocationListener listener) {
        if (mLocationManager != null) {
            mLocationManager.removeUpdates(listener);
            mLocationManager.destory();
            mLocationManager = null;
        }
        if (mManager != null) {
            mManager.removeUpdates(listener);
        }
    }
}

設計上的巧思

這個類別有兩個實用的細節值得學習。第一,它會依當前的網路型別(例如 Wi-Fi)選擇最適合的定位來源,並優先採用「最後已知位置」,能大幅加快首次定位的速度。第二,當取不到最後已知位置時,才透過 Criteria 描述需求(粗精度、不需要海拔與方位、不計成本),請求最佳 provider 持續更新。

最後別忘了成對的 disableMyLocation():一旦不再需要定位,就移除更新並釋放資源,避免背景持續耗電。把「取得經緯度」與「反查地名」這兩件事 respectively 封裝好,之後在任何頁面都能輕鬆呼叫。

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