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

Android 快速上手高德地圖 SDK(附實戰項目)

編輯:關於 Android 程式設計

近期的項目裡需要用到高德地圖與定位功能,學習過程中我翻了不少文檔和 Demo 代碼,也踩了一些坑(部分文檔著實讓人費解,示例代碼連註釋都欠奉,上下文還對不上)。因此乾脆把最直白的步驟整理成文,希望能幫還不太熟悉高德 SDK 的朋友少走彎路、提高效率。

本文將介紹高德地圖 SDK 的完整使用流程,從獲取 Key、導包、配置權限,到布局與編碼實現,並重點演示兩個最常用的功能:定位自身位置,以及根據地名或坐標進行搜索定位並顯示小藍點。

一、獲取高德 Key

登入高德開放平台控制台,點擊「創建應用」,填寫應用名稱與應用類型。應用創建完成後,點擊「添加 Key」開始配置。

其中需要填寫 SHA1 值。獲取方式有兩種:Eclipse 用戶可直接在 Preferences → Android → Build 中查看;Android Studio 用戶則可以用下面這個方法,一行代碼即可打印出當前應用的 SHA1:

public static String sHA1(Context context) {
    try {
        PackageInfo info = context.getPackageManager().getPackageInfo(
            context.getPackageName(), PackageManager.GET_SIGNATURES);
        byte[] cert = info.signatures[0].toByteArray();
        MessageDigest md = MessageDigest.getInstance("SHA1");
        byte[] publicKey = md.digest(cert);
        StringBuffer hexString = new StringBuffer();
        for (int i = 0; i < publicKey.length; i++) {
            String appendString = Integer.toHexString(0xFF & publicKey[i]).toUpperCase(Locale.US);
            if (appendString.length() == 1) hexString.append("0");
            hexString.append(appendString);
            hexString.append(":");
        }
        String result = hexString.toString();
        return result.substring(0, result.length() - 1);
    } catch (Exception e) { e.printStackTrace(); }
    return null;
}

提交後即可獲得一串用於開發的 Key。

二、導包

Eclipse 直接把 jar 包放進 libs 即可;Android Studio 則放到 libs 後再 add 到 library。需要引入地圖、定位、搜索等相關的 jar 包。

三、添加權限

把所需的權限都添加到 AndroidManifest.xml 中:

<!-- 網絡定位 -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!-- GPS 定位 -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- 獲取運營商信息 -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- 訪問 WiFi 信息,用於網絡定位 -->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<!-- 訪問網絡 -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- 讀取手機狀態 -->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<!-- 寫入擴展存儲,緩存定位數據 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

四、編碼實現

首先在布局文件中設置高德 SDK 指定的 MapView:

<com.amap.api.maps.MapView
    android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1" />

接着在代碼中初始化 MapView。它承擔着「地圖的 View」這一角色,需要代管地圖的生命週期:

mMapView = (MapView) v.findViewById(R.id.map);
mMapView.onCreate(savedInstanceState); // 在 Activity 的 onCreate 中調用

真正起控制作用的是 AMap 類,可在初始化時完成一系列設置:

if (aMap == null) {
    aMap = mMapView.getMap();
    aMap.moveCamera(CameraUpdateFactory.zoomTo(0)); // 縮放為0,一進來顯示整個中國
    aMap.setLocationSource(this);                    // 設置定位監聽
    aMap.getUiSettings().setMyLocationButtonEnabled(true); // 顯示默認定位按鈕
    aMap.setMyLocationEnabled(true);                 // 顯示定位層並可觸發定位
    aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
}

實現當前位置的小藍點:讓當前 Activity 實現 AMapLocationListener,並重寫定位回調:

@Override
public void onLocationChanged(AMapLocation amapLocation) {
    if (mListener != null && amapLocation != null) {
        if (amapLocation.getErrorCode() == 0) {
            mListener.onLocationChanged(amapLocation); // 顯示系統小藍點
        } else {
            String errText = "定位失敗," + amapLocation.getErrorCode() + ": " + amapLocation.getErrorInfo();
            Log.e("AmapErr", errText);
        }
    }
}

實現地理編碼(輸入地名定位到具體位置):由於 aMap 初始化時設置了定位監聽,當前 Activity 需實現 LocationSource 接口,並重寫激活與停止定位兩個方法:

@Override
public void activate(OnLocationChangedListener listener) {
    mListener = listener;
    if (mLocationClient == null) {
        mLocationClient = new AMapLocationClient(getActivity());
        mLocationOption = new AMapLocationClientOption();
        mLocationClient.setLocationListener(this);
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationClient.setLocationOption(mLocationOption);
        mLocationClient.startLocation();
    }
}

@Override
public void deactivate() {
    mListener = null;
    if (mLocationClient != null) {
        mLocationClient.stopLocation();
        mLocationClient.onDestroy();
    }
    mLocationClient = null;
}

接著聲明並初始化搜索組件:

private GeocodeSearch geocoderSearch;
private Marker geoMarker;

// onCreate 中初始化
geocoderSearch = new GeocodeSearch(getActivity());
geocoderSearch.setOnGeocodeSearchListener(this);
geoMarker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f)
    .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));

具體的地理編碼方法如下:

public void getLatlon(final String name) {
    // 第一個參數為地址,第二個參數為城市(0086 表示全國範圍)
    GeocodeQuery query = new GeocodeQuery(name, "0086");
    geocoderSearch.getFromLocationNameAsyn(query);
}

這裡我把城市參數設為 0086(中國區號),便能實現全國範圍查找;若設成某個城市的區號,則只能查到該城市的地名。

隨後會回調搜索監聽方法完成定位:

@Override
public void onGeocodeSearched(GeocodeResult result, int rCode) {
    if (rCode == 1000) {
        if (result != null && result.getGeocodeAddressList() != null && result.getGeocodeAddressList().size() > 0) {
            GeocodeAddress address = result.getGeocodeAddressList().get(0);
            aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
                AMapUtil.convertToLatLng(address.getLatLonPoint()), 15));
            geoMarker.setPosition(AMapUtil.convertToLatLng(address.getLatLonPoint()));
        } else {
            ToastUtil.show(getActivity(), "沒有查詢到結果~!");
        }
    } else {
        ToastUtil.showerror(getActivity(), rCode);
    }
}

至於逆地理編碼,思路與正向地理編碼異曲同工,只是改為傳入坐標值再定位,這裡補充其代碼:

public void getAddress(final LatLonPoint latLonPoint) {
    RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 200, GeocodeSearch.AMAP);
    geocoderSearch.getFromLocationAsyn(query);
}

@Override
public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
    if (rCode == 1000) {
        if (result != null && result.getRegeocodeAddress() != null) {
            addressName = result.getRegeocodeAddress().getFormatAddress() + "附近";
            aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
                AMapUtil.convertToLatLng(latLonPoint), 15));
            regeoMarker.setPosition(AMapUtil.convertToLatLng(latLonPoint));
        }
    }
}

最終實現的效果如圖:

由於涉及項目相關代碼,這裡就不便全部貼出。若還需要更多功能,可參考高德定位 SDK 官方文檔。有任何問題歡迎在評論區留言交流。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved