1、在AndroidManifest.xml文件中加入定位权限: !-- 这个权限用于进行网络定位 --uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /!-- 这个权限用于访问GPS定位 --uses-permission android:na
1、在AndroidManifest.xml文件中加入定位权限:
<!-- 这个权限用于进行网络定位 --> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <!-- 这个权限用于访问GPS定位 --> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
2、创建一个传感器的类,代码如下
package com.example.baidumap; import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; public class MyOrientationListener implements SensorEventListener { private SensorManager mSensorManager; private Context mContext; private Sensor mSensor; private float lastX; public MyOrientationListener(Context context){ this.mContext = context; } @SuppressWarnings("deprecation") public void start(){ mSensorManager = (SensorManager) mContext .getSystemService(Context.SENSOR_SERVICE); if (mSensorManager != null){ // 获得方向传感器 mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION); } if (mSensor != null){ mSensorManager.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_UI); } } public void stop(){ mSensorManager.unregisterListener(this); } @Override public void onAccuracyChanged(Sensor arg0, int arg1){ // TODO Auto-generated method stub } @SuppressWarnings({ "deprecation" }) @Override public void onSensorChanged(SensorEvent event){ if (event.sensor.getType() == Sensor.TYPE_ORIENTATION) { float x = event.values[SensorManager.DATA_X]; if (Math.abs(x - lastX) > 1.0) { if (mOnOrientationListener != null) { mOnOrientationListener.onOrientationChanged(x); } } lastX = x; } } private OnOrientationListener mOnOrientationListener; public void setOnOrientationListener(OnOrientationListener mOnOrientationListener){ this.mOnOrientationListener = mOnOrientationListener; } public interface OnOrientationListener{ void onOrientationChanged(float x); } }
3、在布局文件中加入一个定位的按钮
<Button android:id="@+id/btn_Location" android:text="定位" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:layout_marginTop="10dp" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintTop_toTopOf="parent"/>
4、添加资源文件(该图片原位置在本人的百度云盘(提取码:k5b7)压缩包assets中,拿过来分别放在如下文件中)
5、MainActivity代码(注意:MainActivity继承了iew.OnClickListener接口)
package com.example.baidumap; import androidx.appcompat.app.AppCompatActivity; import android.content.Context; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.baidu.location.BDAbstractLocationListener; import com.baidu.location.BDLocation; import com.baidu.location.LocationClient; import com.baidu.location.LocationClientOption; import com.baidu.mapapi.CoordType; import com.baidu.mapapi.SDKInitializer; import com.baidu.mapapi.map.BaiduMap; import com.baidu.mapapi.map.BitmapDescriptor; import com.baidu.mapapi.map.BitmapDescriptorFactory; import com.baidu.mapapi.map.MapStatusUpdate; import com.baidu.mapapi.map.MapStatusUpdateFactory; import com.baidu.mapapi.map.MapView; import com.baidu.mapapi.map.MyLocationConfiguration; import com.baidu.mapapi.map.MyLocationData; import com.baidu.mapapi.model.LatLng; public class MainActivity extends AppCompatActivity implements View.OnClickListener{ private Context context; private MapView mapView = null; private BaiduMap baiduMap = null; //定位相关 private double mLatitude; private double mLongtitude; private MyOrientationListener myOrientationListener; //方向传感器 private float mCurrentx; //自定义图标 private BitmapDescriptor mIconLocation; private LocationClient mLocationClient; public BDAbstractLocationListener myListener; private LatLng mLastLocationData; private boolean isFirstin = true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SDKInitializer.initialize(getApplicationContext()); setContentView(R.layout.activity_main); SDKInitializer.setCoordType(CoordType.BD09LL); this.context = this; mapView = (MapView)findViewById(R.id.baiduMapView); baiduMap = mapView.getMap(); //获取地图控件引用 initLocation(); button(); } @Override protected void onStart() { super.onStart(); baiduMap.setMyLocationEnabled(true); //开启定位 if (!mLocationClient.isStarted())mLocationClient.start(); myOrientationListener.start(); //开启方向传感器 } @Override protected void onResume() { super.onResume(); mapView.onResume(); } @Override protected void onPause() { super.onPause(); mapView.onPause(); } @Override protected void onStop() { super.onStop(); baiduMap.setMyLocationEnabled(false); //停止定位 mLocationClient.stop(); myOrientationListener.stop(); //停止方向传感器 } @Override protected void onDestroy() { super.onDestroy(); baiduMap.setMyLocationEnabled(false); mapView.onDestroy(); mapView = null; } @Override public void onClick(View view) { SDKInitializer.initialize(getApplicationContext()); switch (view.getId()) { case R.id.btn_Location: { centerToMyLocation(mLatitude, mLongtitude); break; } } } //按钮响应 private void button() { Button btn_lco = (Button) findViewById(R.id.btn_Location); //按钮 btn_lco.setOnClickListener(this); //按钮处理 } //定位 private class MyLocationListener extends BDAbstractLocationListener { @Override public void onReceiveLocation(BDLocation location) { //mapView 销毁后不在处理新接收的位置 if (location == null || mapView == null){ return; } MyLocationData locData = new MyLocationData.Builder() .accuracy(location.getRadius()) // 此处设置开发者获取到的方向信息,顺时针0-360 .direction(mCurrentx).latitude(location.getLatitude()) .longitude(location.getLongitude()).build(); baiduMap.setMyLocationData(locData); //设置自定义图标 MyLocationConfiguration config = new MyLocationConfiguration(MyLocationConfiguration.LocationMode.NORMAL, true, mIconLocation); baiduMap.setMyLocationConfiguration(config); //更新经纬度 mLatitude = location.getLatitude(); mLongtitude = location.getLongitude(); //设置起点 mLastLocationData = new LatLng(mLatitude, mLongtitude); if (isFirstin) { centerToMyLocation(location.getLatitude(), location.getLongitude()); if (location.getLocType() == BDLocation.TypeGpsLocation) { // GPS定位结果 Toast.makeText(context, "定位:"+location.getAddrStr(), Toast.LENGTH_SHORT).show(); } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) { // 网络定位结果 Toast.makeText(context, "定位:"+location.getAddrStr(), Toast.LENGTH_SHORT).show(); } else if (location.getLocType() == BDLocation.TypeOffLineLocation) { // 离线定位结果 Toast.makeText(context, "定位:"+location.getAddrStr(), Toast.LENGTH_SHORT).show(); } else if (location.getLocType() == BDLocation.TypeServerError) { Toast.makeText(context, "定位:服务器错误", Toast.LENGTH_SHORT).show(); } else if (location.getLocType() == BDLocation.TypeNetWorkException) { Toast.makeText(context, "定位:网络错误", Toast.LENGTH_SHORT).show(); } else if (location.getLocType() == BDLocation.TypeCriteriaException) { Toast.makeText(context, "定位:手机模式错误,请检查是否飞行", Toast.LENGTH_SHORT).show(); } isFirstin = false; } } } //初始化定位 private void initLocation() { //缩放地图 MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(15.0f); baiduMap.setMapStatus(msu); //开启定位 baiduMap.setMyLocationEnabled(true); //声明LocationClient类 mLocationClient = new LocationClient(this); //通过LocationClientOption设置LocationClient相关参数 LocationClientOption option = new LocationClientOption(); option.setOpenGps(true); // 打开gps option.setCoorType("bd09ll"); // 设置坐标类型 option.setIsNeedAddress(true);//设置是否需要地址信息 option.setScanSpan(1000); //设置locationClientOption mLocationClient.setLocOption(option); myListener = new MyLocationListener(); //注册监听函数 mLocationClient.registerLocationListener(myListener); //初始化图标 mIconLocation = BitmapDescriptorFactory.fromResource(R.drawable.navi_map_gps); initOrientation(); //开始定位 mLocationClient.start(); } //回到定位中心 private void centerToMyLocation(double latitude, double longtitude) { baiduMap.clear(); mLastLocationData = new LatLng(latitude, longtitude); MapStatusUpdate msu = MapStatusUpdateFactory.newLatLng(mLastLocationData); baiduMap.animateMapStatus(msu); } //传感器 private void initOrientation() { //传感器 myOrientationListener = new MyOrientationListener(context); myOrientationListener.setOnOrientationListener(new MyOrientationListener.OnOrientationListener() { @Override public void onOrientationChanged(float x) { mCurrentx = x; } }); } }
6、启动项目
7、附上本章的项目(提取码:jl2v)。