一、功能说明
- 掌握Android定位的基本概念,能编写定位过程;
- 掌握第三方地图调用的基本概念,查看第三方官方文档,能实现基础地图调用操作。
- 需实现的具体功能为:百度地图调用及定位。
二、设计分析与核心代码
1 注册和获取密钥
配置开发秘钥,这里就不展开了
2 Android Studio配置
在百度地图官方网站中下载Android地图SDK,并导入项目中使用。
3 配置AndroidManifest.xml文件
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mybaidumap">
<application
android:name=".DemoApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.baidu.lbsapi.API_KEY"
android:value="OKC9aGS3foO00qP86rVkXlyKGxrYfZlD" />
<service android:name="com.baidu.location.f"
android:enabled="true"
android:process=":remote"/>
</application>
<!-- 访问网络,进行地图相关业务数据请求,包括地图数据,路线规划,POI检索等 -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- 获取网络状态,根据网络状态切换进行数据请求网络转换 -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- 读取外置存储。如果开发者使用了so动态加载功能并且把so文件放在了外置存储区域,则需要申请该权限,否则不需要 -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<!-- 写外置存储。如果开发者使用了离线地图,并且数据写在外置存储区域,则需要申请该权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!-- 这个权限用于进行网络定位 -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!-- 这个权限用于访问GPS定位 -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
</manifest>
4 在布局文件中添加地图容器,并使用FrameLayout布局在地图上方显示定位信息的经纬度和地址
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<!--百度地图控件-->
<com.baidu.mapapi.map.MapView
android:id="@+id/bmapView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clickable="true" />
<!--位置文本布局的背景色代码的前2位代码为透明度-->
<LinearLayout
android:layout_width="394dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:background="@android:color/background_light"
android:orientation="vertical">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="12dp"
android:layout_marginTop="20dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="纬度:"
android:textColor="#000000"
android:textSize="15dp" />
<TextView
android:id="@+id/tv_Lat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textColor="#000000"
android:textSize="15dp" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="12dp"
android:layout_marginTop="10dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="经度:"
android:textColor="#000000"
android:textSize="15dp" />
<TextView
android:id="@+id/tv_Lon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textColor="#000000"
android:textSize="15dp" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="12dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="地址:"
android:textColor="#000000"
android:textSize="15dp" />
<TextView
android:id="@+id/tv_Add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textColor="#000000"
android:textSize="15dp" />
</LinearLayout>
</LinearLayout>
</FrameLayout>
5 地图初始化
在使用SDK各组件之前初始化context信息,传入ApplicationContext
6 创建地图Activity,管理MapView生命周期
7 判断应用是否具有定位权限。如果没有,则动态申请;如果有,则发起定位
8 LocationListener添加百度位置监听器
private class MyLocationListener implements BDLocationListener {
@Override
public void onReceiveLocation(BDLocation bdLocation) {
tv_Lat.setText(bdLocation.getLatitude()+"");
tv_Lon.setText(bdLocation.getLongitude()+"");
tv_Add.setText(bdLocation.getAddrStr());
if(bdLocation.getLocType()==BDLocation.TypeGpsLocation || bdLocation.getLocType()==BDLocation.TypeNetWorkLocation){
navigateTo(bdLocation);
}
}
}
9 初始化定位数据
private void initLocation() { //初始化
MyLocationListener myLocationListener= new MyLocationListener();
mLocationClient = new LocationClient(getApplicationContext());
mLocationClient.registerLocationListener(myLocationListener);
SDKInitializer.initialize(getApplicationContext());
setContentView(R.layout.activity_main);
mapView = findViewById(R.id.bmapView);
baiduMap = mapView.getMap();
baiduMap.setMyLocationEnabled(true);
tv_Lat = findViewById(R.id.tv_Lat);
tv_Lon = findViewById(R.id.tv_Lon);
tv_Add = findViewById(R.id.tv_Add);
/**
* 对定位的图标进行配置,需要MyLocationConfiguration实例,这个类是用设置定位图标的显示方式的
*/
MyLocationConfiguration config=new MyLocationConfiguration(MyLocationConfiguration.LocationMode.NORMAL, true, BitmapDescriptorFactory.fromResource(R.drawable.location));
baiduMap.setMyLocationConfiguration(config);
LocationClientOption option = new LocationClientOption();
option.setOpenGps(true); // 打开gps
option.setCoorType("bd09ll"); // 设置坐标类型
option.setScanSpan(1000);//设置扫描时间间隔
//设置定位模式,三选一
option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
/*option.setLocationMode(LocationClientOption.LocationMode.Battery_Saving);
option.setLocationMode(LocationClientOption.LocationMode.Device_Sensors);*/
//设置需要地址信息
option.setIsNeedAddress(true);
//保存定位参数
mLocationClient.setLocOption(option);
}
10 MainActivity.java中开启定位图层,并关联监听器
public class MainActivity extends AppCompatActivity {
private MapView mMapView = null;
private BaiduMap mBaiduMap = null;
private LocationClient mLocationClient = null;
// 是否是第一次定位
private boolean isFirstLocate = true;
// 当前定位模式
private MyLocationConfiguration.LocationMode locationMode;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取地图控件引用
mMapView = (MapView) findViewById(R.id.bmapView);
// 得到地图
mBaiduMap = mMapView.getMap();
// 开启地图定位图层
mBaiduMap.setMyLocationEnabled(true);
// 动态申请权限
List<String> permissionList = new ArrayList<>();
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
}
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
permissionList.add(Manifest.permission.READ_PHONE_STATE);
}
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
if (!permissionList.isEmpty()) {
String[] permissions = permissionList.toArray(new String[permissionList.size()]);
ActivityCompat.requestPermissions(MainActivity.this, permissions, 1);
}
//定位初始化
mLocationClient = new LocationClient(this);
//通过LocationClientOption设置LocationClient相关参数
LocationClientOption option = new LocationClientOption();
option.setOpenGps(true); // 打开gps
option.setCoorType("bd09ll"); // 设置坐标类型
option.setScanSpan(1000);
option.setIsNeedAddress(true); // 设置地址信息
option.setIsNeedLocationDescribe(true);//设置是否需要地址描述
//设置locationClientOption
mLocationClient.setLocOption(option);
locationMode = MyLocationConfiguration.LocationMode.FOLLOWING;
//注册LocationListener监听器
MyLocationListener myLocationListener = new MyLocationListener();
mLocationClient.registerLocationListener(myLocationListener);
//开启地图定位图层
mLocationClient.start();
}
public class MyLocationListener extends BDAbstractLocationListener {
@Override
public void onReceiveLocation(BDLocation location) {
//mapView 销毁后不在处理新接收的位置
if (location == null || mMapView == null){
return;
}
// 如果是第一次定位
LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
if (isFirstLocate) {
isFirstLocate = false;
//给地图设置状态
mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newLatLng(ll));
}
MyLocationData locData = new MyLocationData.Builder()
.accuracy(location.getRadius())
// 此处设置开发者获取到的方向信息,顺时针0-360
.direction(location.getDirection()).latitude(location.getLatitude())
.longitude(location.getLongitude()).build();
mBaiduMap.setMyLocationData(locData);
}
}
@Override
protected void onResume() {
super.onResume();
//在activity执行onResume时执行mMapView. onResume (),实现地图生命周期管理
mMapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
//在activity执行onPause时执行mMapView. onPause (),实现地图生命周期管理
mMapView.onPause();
}
@Override
protected void onDestroy() {
mLocationClient.stop();
mBaiduMap.setMyLocationEnabled(false);
mMapView.onDestroy();
mMapView = null;
super.onDestroy();
}
}
要注意的内容:
1)BaiduMap组件需要和MapView容器相关联:mBaiduMap = mMapView.getMap();否则定位无法显示
2)添加动态申请权限代码
三、界面展示
四、源码参考
https://gitee.com/xiao-tangtao/MyBaiduMap
https://blog.csdn.net/qq_44677790/article/details/111087393