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

Android 百度地圖開發:由地址取得經緯度的兩種寫法

Android 百度地圖開發之通過地址獲得經緯度

做百度地圖開發時,常需要從一個地址字串換算出經緯度。以下整理兩種做法。

方法一:Geocoder

public GeoPoint getGeoPointBystr(String str) {
    GeoPoint gpGeoPoint = null;
    if (str != null) {
        Geocoder gc = new Geocoder(MyMapActivity.this, Locale.CHINA);
        List<Address> addressList = null;
        try {
            addressList = gc.getFromLocationName(str, 1);
            if (!addressList.isEmpty()) {
                Address address_temp = addressList.get(0);
                // 計算經緯度
                double Latitude  = address_temp.getLatitude()  * 1E6;
                double Longitude = address_temp.getLongitude() * 1E6;
                System.out.println("經度:" + Latitude);
                System.out.println("緯度:" + Longitude);
                // 產生 GeoPoint
                gpGeoPoint = new GeoPoint((int)Latitude, (int)Longitude);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return gpGeoPoint;
}

這個方法只需傳入一個(合法)地址字串,回傳一個 GeoPoint 物件,再用 getLatitude()/getLongitude() 就能取得經緯度。注意 GeoPoint 內部使用「度 × 10⁶」的整數表示,所以這裡要乘上 1E6。

值得注意的是,以上寫法存在 API 版本問題——2.2 版本就不能用了。

方法二:MKSearch.geocode(個人比較推薦)

mkSearch.geocode("詳細地址", "城市");

這裡的詳細地址可以透過 MKSuggestionInfo 物件的 key 取得,城市則可由該物件的 city 取得。

呼叫之後,會在實作 MKSearchListener 介面的類別中觸發:

public void onGetAddrResult(MKAddrInfo info, int error) {
    // TODO Auto-generated method stub
    System.out.println("經緯度:" + info.geoPt.getLatitudeE6() + "  "
                                  + info.geoPt.getLongitudeE6());
}

這樣就能拿到經緯度了。相比 Geocoder,MKSearch 是百度 SDK 自己的服務,不必依賴系統的地理編碼器,在不同版本與不同機型上的可用性都更穩定。

更多 Android 相關資訊見 Android 專題頁面 https://www.linuxidc.com/topicnews.aspx?tid=11。

Copyright © Linux教程網 All Rights Reserved