1. 程式人生 > >整合高德地圖SDK實現實時定位

整合高德地圖SDK實現實時定位

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
    <uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

    <application
        android:name=".MyApplication"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.NoTitleBar">
        <!--高德地圖配置部分-->
        <meta-data
            android:name="com.amap.api.v2.apikey"
            android:value="e2c5e5e53f55b03a8da60ceb0574d45d"/>
        <!--高德地圖配置service-->
        <service android:name=".service.GaodeMapService"/>
<span style="white-space:pre">	</span>...

<pre name="code" class="java"><application
這個Service是用來後臺定位的。大家如果需要就新增建立一個Service並且進行配置。

第四步:建立一個MapUtils.java工具類。具體程式碼如下:

public class MapUtils {
	/**
	 *  開始定位
	 */
	public final static int MSG_LOCATION_START = 0;
	/**
	 * 定位完成
	 */
	public final static int MSG_LOCATION_FINISH = 1;
	/**
	 * 停止定位
	 */
	public final static int MSG_LOCATION_STOP= 2;
	
	public final static String KEY_URL = "URL";
	public final static String URL_H5LOCATION = "file:///android_asset/location.html";
	/**
	 * 根據定位結果返回定位資訊的字串
	 * @param loc
	 * @return
	 */
	public synchronized static String getLocationStr(AMapLocation location){
		if(null == location){
			return null;
		}
		StringBuffer sb = new StringBuffer();
		//errCode等於0代表定位成功,其他的為定位失敗,具體的可以參照官網定位錯誤碼說明
		if(location.getErrorCode() == 0){
			sb.append("定位成功" + "\n");
			sb.append("定位型別: " + location.getLocationType() + "\n");
			sb.append("經    度    : " + location.getLongitude() + "\n");
			sb.append("緯    度    : " + location.getLatitude() + "\n");
			sb.append("精    度    : " + location.getAccuracy() + "米" + "\n");
			sb.append("提供者    : " + location.getProvider() + "\n");
			
			if (location.getProvider().equalsIgnoreCase(
					android.location.LocationManager.GPS_PROVIDER)) {
				// 以下資訊只有提供者是GPS時才會有
				sb.append("速    度    : " + location.getSpeed() + "米/秒" + "\n");
				sb.append("角    度    : " + location.getBearing() + "\n");
				// 獲取當前提供定位服務的衛星個數
				sb.append("星    數    : "
						+ location.getSatellites() + "\n");
			} else {
				// 提供者是GPS時是沒有以下資訊的
				sb.append("國    家    : " + location.getCountry() + "\n");
				sb.append("省            : " + location.getProvince() + "\n");
				sb.append("市            : " + location.getCity() + "\n");
				sb.append("城市編碼 : " + location.getCityCode() + "\n");
				sb.append("區            : " + location.getDistrict() + "\n");
				sb.append("區域 碼   : " + location.getAdCode() + "\n");
				sb.append("地    址    : " + location.getAddress() + "\n");
				sb.append("興趣點    : " + location.getPoiName() + "\n");
				//定位完成的時間
				sb.append("定位時間: " + formatUTC(location.getTime(), "yyyy-MM-dd HH:mm:ss") + "\n");
			}
		} else {
			//定位失敗
			sb.append("定位失敗" + "\n");
			sb.append("錯誤碼:" + location.getErrorCode() + "\n");
			sb.append("錯誤資訊:" + location.getErrorInfo() + "\n");
			sb.append("錯誤描述:" + location.getLocationDetail() + "\n");
		}
		//定位之後的回撥時間
		sb.append("回撥時間: " + formatUTC(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss") + "\n");
		return sb.toString();
	}
	
	private static SimpleDateFormat sdf = null;
	public synchronized static String formatUTC(long l, String strPattern) {
		if (TextUtils.isEmpty(strPattern)) {
			strPattern = "yyyy-MM-dd HH:mm:ss";
		}
		if (sdf == null) {
			try {
				sdf = new SimpleDateFormat(strPattern, Locale.CHINA);
			} catch (Throwable e) {
			}
		} else {
			sdf.applyPattern(strPattern);
		}
		return sdf == null ? "NULL" : sdf.format(l);
	}
}
第五步:在Activity中進行位置定位。具體程式碼如下:
    //得到地理位置方法
    private synchronized void getLocation(Context context){
        Log.e("TAG","正在執行獲取getLocation方法");
        //宣告AMapLocationClient類物件
        AMapLocationClient mLocationClient = null;
        AMapLocationClientOption locationClientOption = new AMapLocationClientOption();
        //設定為高精度
        locationClientOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //設定預設返回地址
        locationClientOption.setNeedAddress(true);
        //設定是否只定位一次
        locationClientOption.setOnceLocation(true);
        if(locationClientOption.isOnceLocation()){
            locationClientOption.setOnceLocationLatest(true);
        }
        //設定是否強制重新整理WiFi
        locationClientOption.setWifiActiveScan(true);
        //設定是否允許模擬位置,預設為false,不允許模擬位置
        locationClientOption.setMockEnable(true);
        //設定定位間隔,單位毫秒,預設為2000ms
        locationClientOption.setInterval(2000);
        //初始化定位
        mLocationClient = new AMapLocationClient(context);
        //為定位進行設定
        mLocationClient.setLocationOption(locationClientOption);
        //設定定位回撥監聽
        mLocationClient.setLocationListener(mAMapLocationListener);
        //啟動定位
        mLocationClient.startLocation();

    }
    AMapLocationListener mAMapLocationListener = new AMapLocationListener(){
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    s =   MapUtils.getLocationStr(amapLocation);
                    edt_show_location.setText(s);
                }
            }
        }
    };
在上面程式碼中,首先獲取一個獲取位置的服務類AMapLocationClient物件,然後獲取一個配置AMapLocationClientOption類物件進行配置。然後把
AMapLocationClientOption的設定結果設定到AMapLocationClient物件中。然後開始獲取定位。結果會在回撥介面中獲取到。
這樣我們就獲取了我們的地理位置。然後我們可以自行對獲取到的資訊進行擷取。地理位置獲取的形式如下:
好了,上面我們就完成了一次地理定位了。程式碼要注意的一點回調介面是採用非同步的回撥,需要把回撥放在方法外面例項化。為的就在監聽中進行UI的更新,請看上面的程式碼。Android6.0需要進行執行許可權檢查。
具體請看SDK中的Demo裡面許可權檢查類用法。