首先是搭建环境,这就不多说了,官方传送门 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中,用到的权限主要有以下几个
android:name="com.android.launcher.permission.READ_SETTINGS" />
android:name="android.permission.ACCESS_COARSE_LOCATION" />
android:name="android.permission.ACCESS_FINE_LOCATION" />
android:name="android.permission.ACCESS_WIFI_STATE" />
android:name="android.permission.ACCESS_NETWORK_STATE" />
android:name="android.permission.WRITE_SETTINGS" />
android:name="android.permission.READ_PHONE_STATE" />
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
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; } }
最后,运行结果