Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Android 定位實作:用經緯度取得地理位置與地址資訊

第一步:取得 LocationManager 與 Criteria

Android 的定位服務由系統的 LocationManager 統籌,而 Criteria 用來描述「你想要什麼樣的定位來源」——精度要多高、要不要海拔、耗不耗電。設定好條件後交給 getBestProvider(),系統就會挑一個最合適的提供者(GPS 或網路)。

LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager) getSystemService(context);

Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);   // 精確模式
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(false);
criteria.setPowerRequirement(Criteria.POWER_LOW);

String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);

Criteria 的查詢條件

  • setAccuracy(int):解析精度。ACCURACY_FINE 為精確模式,ACCURACY_COARSE 為模糊模式。
  • setAltitudeRequired(boolean):是否要求海拔高度資訊。
  • setBearingRequired(boolean):是否要求方向資訊。
  • setCostAllowed(boolean):是否允許計費的定位方式。
  • setPowerRequirement(int):耗電程度,可為 NO_REQUIREMENT、POWER_LOW、POWER_MEDIUM、POWER_HIGH。
  • setSpeedRequired(boolean):是否要求速度資訊。

第二步:把經緯度轉成人看得懂的地址

拿到 Location 後,用 getLatitude() 與 getLongitude() 取出座標,再交給 Geocoder 反查地址。以下 function 會把座標與地址一併顯示在 TextView 上:

private void updateWithNewLocation(Location location) {
    String coordinate;
    TextView loc = (TextView) findViewById(R.id.loc);
    String addressStr = "no address \n";

    if (location != null) {
        double lat = location.getLatitude();
        double lng = location.getLongitude();
        coordinate = "Latitude:" + lat + "\nLongitude:" + lng;

        Geocoder geocoder = new Geocoder(context, Locale.getDefault());
        try {
            List<Address> addresses =
                    geocoder.getFromLocation(lat, lng, 1);
            StringBuilder sb = new StringBuilder();
            if (addresses.size() > 0) {
                Address address = addresses.get(0);
                for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
                    sb.append(address.getAddressLine(i)).append("\n");
                }
                sb.append(address.getLocality()).append("\n");
                sb.append(address.getCountryName());
                addressStr = sb.toString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        coordinate = "no coordinate!\n";
    }

    loc.setText("your coordinate:\n" + coordinate + "\n" + addressStr);
}

三個容易踩到的坑

其一,getLastKnownLocation() 取的是「最後一次已知位置」,可能很舊甚至為 null,正式 App 應該用 requestLocationUpdates() 或 Fused Location Provider 持續更新。其二,Geocoder 是同步且需要網路的呼叫,放在主執行緒會造成 ANR,請移到背景執行緒。其三,务必在清單檔註冊 ACCESS_FINE_LOCATION(或 ACCESS_COARSE_LOCATION),並在執行期向使用者請求權限,否則 location 永遠是 null。

Copyright © Linux教程網 All Rights Reserved