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

Android GPS 定位並獲取所在城市信息

編輯:關於 Android 程式設計

獲取用戶所在城市通常分為兩個步驟:先取得當前位置的經度與緯度,再根據經緯度轉換為城市名稱。本文將逐步說明。

一、取得當前經緯度

添加定位權限

使用 GPS 前需在清單文件中加入定位權限:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>

檢查 GPS 是否開啟

先判斷 GPS 模塊是否可用,若未開啟則引導用戶前往設置頁開啟:

private void openGPSSettings() {
    LocationManager alm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    if (alm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
        Toast.makeText(this, "GPS 模塊正常", Toast.LENGTH_SHORT).show();
        return;
    }
    Toast.makeText(this, "請開啟 GPS!", Toast.LENGTH_SHORT).show();
    startActivityForResult(new Intent(Settings.ACTION_SECURITY_SETTINGS), 0);
}

獲取位置

通過 Criteria 選擇合適的定位提供者,再讀取位置並註冊監聽器以實時更新:

private void getLocation() {
    LocationManager locationManager =
        (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);       // 高精度
    criteria.setPowerRequirement(Criteria.POWER_LOW);   // 低功耗
    String provider = locationManager.getBestProvider(criteria, true);
    Location location = locationManager.getLastKnownLocation(provider);
    updateToNewLocation(location);
    locationManager.requestLocationUpdates(provider, 100 * 1000, 500, locationListener);
}

顯示經緯度

private void updateToNewLocation(Location location) {
    TextView tv1 = (TextView) this.findViewById(R.id.tv1);
    if (location != null) {
        double latitude = location.getLatitude();
        double longitude = location.getLongitude();
        tv1.setText("維度:" + latitude + "\n經度:" + longitude);
    } else {
        tv1.setText("無法獲取地理信息");
    }
}

二、根據經緯度轉換城市名稱

經緯度轉城市名稱需要依賴地圖服務,目前主要有百度地圖與谷歌地圖兩種選擇。百度地圖需註冊賬號並申請 APP_KEY,谷歌地圖可直接調用。

百度地圖接口:

https://api.map.baidu.com/geocoder?output=json&location=緯度,經度&key=APP_KEY

谷歌地圖接口:

https://maps.google.com/maps/api/geocode/json?latlng=緯度,經度&language=zh-CN&sensor=true

兩者都支持返回 JSON 或 XML 格式。以百度返回的 JSON 為例,其中 addressComponent 字段就包含了省、市、區、街道等結構化信息:

{
  "status": "OK",
  "result": {
    "formatted_address": "河南省洛陽市嵩縣洛欏線",
    "addressComponent": {
      "city": "洛陽市",
      "district": "嵩縣",
      "province": "河南省",
      "street": "洛欏線"
    },
    "cityCode": 153
  }
}

而谷歌返回的 JSON 則把各級行政信息放在 results 數組的 address_components 中,並以 types 標明其類型(如 locality 表示城市、administrative_area_level_1 表示省份等),解析時按需選取即可。

注意事項

  • 獲取位置與網絡請求均需在獲得授權後、並在合適的線程中執行。
  • 百度、谷歌的接口地址與返回格式可能隨版本變化,實際開發請以官方最新文檔為準。
  • 示例中的坐標轉地址示例數據僅供參考,真實結果以接口返回為準。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved