高德地圖地理編碼和逆地理編碼

最近在使用到高德地圖這塊地理編碼和逆地理編碼,感覺非常好用.
一,首先要導入高德地圖SDK,高德開放者平臺有詳細的介紹,和如何獲取key的方式
二,地理編碼和逆地理編碼比較簡單直接上代碼了,有些重要的意見通過註釋說明了.在這上面沒有UI,直接通過toast出來了.

/**
 * 地理編碼與逆地理編碼功能介紹
 */
public class GeocoderActivity extends Activity implements OnGeocodeSearchListener {
    private GeocodeSearch geocoderSearch;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LatLonPoint latLonPoint = new LatLonPoint(39.90865, 116.39751); //創建經緯度LatLonPoint
        /*
         * 設置離線地圖存儲目錄,在下載離線地圖或初始化地圖設置;
         * 使用過程中可自行設置, 若自行設置了離線地圖存儲的路徑,
         * 則需要在離線地圖下載和使用地圖頁面都進行路徑設置
         * */
        //Demo中爲了其他界面可以使用下載的離線地圖,使用默認位置存儲,屏蔽了自定義設置
//        MapsInitializer.sdcardDir =OffLineMapUtils.getSdCacheDir(this);
        init();
        getLatlon("中關村","北京");
        getAddress(latLonPoint);
    }

    /**
     * 初始化
     */
    private void init() {
        geocoderSearch = new GeocodeSearch(this);
        geocoderSearch.setOnGeocodeSearchListener(this);
    }

    /**
     * 響應地理編碼
     */
    public void getLatlon(String name,String city) {
        // 第一個參數表示地址,第二個參數表示查詢城市,中文或者中文全拼,citycode、adcode,
        GeocodeQuery query = new GeocodeQuery(name, city);
        geocoderSearch.getFromLocationNameAsyn(query);// 設置同步地理編碼請求
    }
    /**
     * 響應逆地理編碼
     */
    public void getAddress(LatLonPoint latLonPoint) {
        // 第一個參數表示一個Latlng,第二參數表示範圍多少米,第三個參數表示是火系座標系還是GPS原生座標系
        RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 200, GeocodeSearch.AMAP);
        geocoderSearch.getFromLocationAsyn(query);// 設置異步逆地理編碼請求
    }
    /**
     * 地理編碼查詢回調  result獲取的結果 rCode爲狀態碼
     */
    @Override
    public void onGeocodeSearched(GeocodeResult result, int rCode) {
        if (rCode == AMapException.CODE_AMAP_SUCCESS) {
            if (result != null && result.getGeocodeAddressList() != null
                    && result.getGeocodeAddressList().size() > 0) {
                GeocodeAddress address = result.getGeocodeAddressList().get(0);
                LatLonPoint latLonPoint = address.getLatLonPoint();
                Toast.makeText(this, "latLonPoint"+latLonPoint, Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 逆地理編碼回調 result獲取的結果 rCode爲狀態碼
     */
    @Override
    public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
        if (rCode == AMapException.CODE_AMAP_SUCCESS) {
            if (result != null && result.getRegeocodeAddress() != null
                    && result.getRegeocodeAddress().getFormatAddress() != null) {
                String address = result.getRegeocodeAddress().getFormatAddress()
                        + "附近";
                Toast.makeText(this, "address"+address, Toast.LENGTH_SHORT).show();
            }
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章