首先是搭建環境,這就不多說了,官方傳送門 http://lbsyun.baidu.com/index.php?title=android-locsdk/guide/v5-0
接着 初始化地圖
private void init(){ // 地圖初始化 mMapView.setVisibility(View.VISIBLE); mBaiduMap = mMapView.getMap(); // 開啓定位圖層 mBaiduMap.setMyLocationEnabled(true); // 定位初始化 mLocClient = new LocationClient(this); mLocClient.registerLocationListener(myListener); LocationClientOption option = new LocationClientOption(); option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy); option.setOpenGps(true); // 打開gps option.setCoorType("bd09ll"); // 設置座標類型 option.setScanSpan(1000); mLocClient.setLocOption(option) mLocClient.start(); mCurrentMode = LocationMode.COMPASS; mBaiduMap .setMyLocationConfigeration(new MyLocationConfiguration( mCurrentMode, true, null)); }
3定位SDK的監聽函數:
/** * 定位SDK監聽函數 */ public class MyLocationListenner implements BDLocationListener { @Override public void onReceiveLocation(BDLocation location) { // map view 銷燬後不在處理新接收的位置 if (location == null || mMapView == null) { return; } MyLocationData locData = new MyLocationData.Builder() .accuracy(location.getRadius()) // 此處設置開發者獲取到的方向信息,順時針0-360 .direction(100).latitude(location.getLatitude()) .longitude(location.getLongitude()).build(); mBaiduMap.setMyLocationData(locData); if (isFirstLoc) { isFirstLoc = false; LatLng ll = new LatLng(location.getLatitude(), location.getLongitude()); MapStatus.Builder builder = new MapStatus.Builder(); builder.target(ll).zoom(18.0f); mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build())); } } public void onReceivePoi(BDLocation poiLocation) { } }到這裏,如果我們直接運行的話,在android 6以下是運行成功的,在android 6以上會出現運行失敗的情況,運行失敗的原因在於android 6.0採用了運行時權限(android-RuntimePermissions),6.0的權限一般分爲兩種,一種時普通權限,如下圖:其他的爲運行時權限
在百度地圖API中,用到的權限主要有以下幾個
<uses-permission android:name="com.android.launcher.permission.READ_SETTINGS" /> <!-- 這個權限用於進行網絡定位 --> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <!-- 這個權限用於訪問GPS定位 --> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <!-- 用於訪問wifi網絡信息,wifi信息會用於進行網絡定位 --> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <!-- 獲取運營商信息,用於支持提供運營商信息相關的接口 --> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.WRITE_SETTINGS" /> <!-- 用於讀取手機當前的狀態 --> <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <!-- 寫入擴展存儲,向擴展卡寫入數據,用於寫入離線定位數據 --> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" /> <!-- 訪問網絡,網絡定位需要上網 --> <uses-permission android:name="android.permission.INTERNET" />其中:
Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_PHONE_STATE
這幾個爲運行時權限,需要在運行時得到用戶的授權。
在Activity中進行授權如下:判斷用戶的android版本,如果爲23(6.0),執行showcontacts,提醒用戶授權
if (Build.VERSION.SDK_INT>=23){ showContacts(mMapView); }else{ init(); }
判斷用戶是否已經授權,如果已經授權,直接開始定位,如果沒有授權,
requestContactsPermissions(v);
提示用戶進行授權
public void showContacts(View v) { Log.i(TAG, "Show contacts button pressed. Checking permissions."); // Verify that all required contact permissions have been granted. if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) { // Contacts permissions have not been granted. Log.i(TAG, "Contact permissions has NOT been granted. Requesting permissions."); requestContactsPermissions(v); } else { // Contact permissions have been granted. Show the contacts fragment. Log.i(TAG, "Contact permissions have already been granted. Displaying contact details."); init(); } }
private void requestContactsPermissions(View v) { // BEGIN_INCLUDE(contacts_permission_request) if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_COARSE_LOCATION) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_PHONE_STATE) ) { // Provide an additional rationale to the user if the permission was not granted // and the user would benefit from additional context for the use of the permission. // For example, if the request has been denied previously. Log.i(TAG, "Displaying contacts permission rationale to provide additional context."); // Display a SnackBar with an explanation and a button to trigger the request. Snackbar.make(v, "permission_contacts_rationale", Snackbar.LENGTH_INDEFINITE) .setAction("ok", new View.OnClickListener() { @Override public void onClick(View view) { ActivityCompat .requestPermissions(MainActivity.this, PERMISSIONS_CONTACT, REQUEST_CONTACTS); } }) .show(); } else { // Contact permissions have not been granted yet. Request them directly. ActivityCompat.requestPermissions(this, PERMISSIONS_CONTACT, REQUEST_CONTACTS); } // END_INCLUDE(contacts_permission_request) }
最後,對授權的結果進行判定:
@Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode==REQUEST_CONTACTS){ if (PermissionUtil.verifyPermissions(grantResults)) { init(); } else { } }else{ super.onRequestPermissionsResult(requestCode, permissions, grantResults); } }其中 permissonutil代碼如下
/** * Utility class that wraps access to the runtime permissions API in M and provides basic helper * methods. */ public abstract class PermissionUtil { /** * Check that all given permissions have been granted by verifying that each entry in the * given array is of the value {@link PackageManager#PERMISSION_GRANTED}. * * @see Activity#onRequestPermissionsResult(int, String[], int[]) */ public static boolean verifyPermissions(int[] grantResults) { // At least one result must be checked. if(grantResults.length < 1){ return false; } // Verify that each required permission has been granted, otherwise return false. for (int result : grantResults) { if (result != PackageManager.PERMISSION_GRANTED) { return false; } } return true; } }
最後,運行結果