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

Android 根據當前經緯度獲取所在城市

編輯:關於 Android 程式設計

本文介紹如何借助 Google 地圖服務,通過用戶當前的經度與緯度反查(reverse geocode)出所在城市。

核心思路

整體流程分為兩步:先通過 LocationManager 獲取當前的經緯度坐標,再把坐標提交給地圖服務接口,解析返回的 XML 或 JSON 數據,從中提取城市名稱。由於網絡請求屬於耗時操作,需放到子線程中執行。

獲取當前位置

通過 getLastKnownLocation 取得最近一次已知位置,GPS 不可用時退回網絡定位:

this.locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
currentLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (currentLocation == null)
    currentLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

若只需要獲取一次城市信息而非實時跟蹤,可以註釋掉 requestLocationUpdates 的實時監聽部分,直接使用最近位置即可。

在子線程中解析城市

public void start() {
    if (currentLocation != null) {
        new Thread() {
            public void run() {
                String temp = reverseGeocode(currentLocation);
                if (temp != null && temp.length() >= 2)
                    city = temp;
            }
        }.start();
    }
}

調用地圖接口並解析

reverseGeocode 方法拼接經緯度到 Google 地圖接口的請求 URL,通過 HttpURLConnection 發送請求,再用 SAX 解析返回的 XML:

String url = "https://maps.google.com/maps/geo?q="
    + Double.toString(loc.getLatitude()) + ","
    + Double.toString(loc.getLongitude())
    + "&output=xml&oe=utf8&sensor=true&key=" + GOOGLE_MAPS_API_KEY;

HttpURLConnection connection = (HttpURLConnection) serverAddress.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(10000);
connection.connect();

SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader xr = parser.getXMLReader();
GoogleReverseGeocodeXmlHandler handler = new GoogleReverseGeocodeXmlHandler();
xr.setContentHandler(handler);
xr.parse(new InputSource(connection.getInputStream()));
localityName = handler.getLocalityName();

注意事項

  • 獲取位置需要在清單文件中聲明 ACCESS_FINE_LOCATION 等定位權限。
  • 網絡請求必須在子線程執行,並做好異常與超時處理。
  • 示例中使用的 Google Maps Geocoding 接口為舊版接口,實際開發中建議改用官方推薦的地理編碼 API,並妥善保管 API Key。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved