注意:详解参考代码注释:
参考文档:
1.函数相关类参考:https://lbsyun.baidu.com/index.php?title=android-locsdk/guide/get-location/indoors
2.SDK:https://lbsyun.baidu.com/index.php?title=sdk/download&action
3.源代码:
3.1 AndroidManifest.xml源代码:
3.2 activity_main:
3.3 MainActivity:
总结:
- 由于使用的是基本的定位所以定位不是很精准, 但是基本同理可得,使用全量定位开发包应该即可
- 对于结构:一定复制之后要同步,闭包dependencies记得添加:
implementation files('libs/BaiduLBS_Android.jar')
很重要这个,判断是否lib下的BaiduLBS_Android.jar
还可以展开 - 对于很多类的方法基本开发文档中都有说明,参考可以弄得更加清楚
- 书山有路勤为径,学海无涯苦作舟
一.整体框架;
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.lbstest">
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission
android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"
tools:ignore="ProtectedPermissions" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
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/Theme.LBSTest">
<meta-data
android:name="com.baidu.lbsapi.API_KEY"
android:value="百度申请的apkkey" />
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name="com.baidu.location.f"
android:enabled="true"
android:process=":remote"></service>
</application>
</manifest>
activity_main:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/position_text_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone"/>
<com.baidu.mapapi.map.MapView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/bmapView"
android:clickable="true"/>
</LinearLayout>
MainActivity:
package com.example.lbstest;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import java.util.ArrayList;
import java.util.List;
/**
* @author chenzi
*/
public class MainActivity extends AppCompatActivity {
private LocationClient mLocationClient;
private TextView positionText;
private MapView mapView;
private BaiduMap baiduMap;
private boolean isFirstLocation = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 注册监听事件
mLocationClient = new LocationClient(getApplicationContext());
mLocationClient.registerLocationListener((BDAbstractLocationListener) new MyLocationListener());
// 用于显示地图
SDKInitializer.initialize(getApplicationContext());
setContentView(R.layout.activity_main);
mapView = findViewById(R.id.bmapView);
positionText = findViewById(R.id.position_text_view);
// 地图的总控制器
baiduMap = mapView.getMap();
// 用于注册显示的我的图标
baiduMap.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()) {
// 返回的是false,则是空的,取反则为非空,意思是有权限没有申请
String[] permissions = permissionList.toArray(new String[permissionList.size()]);
// 调用函数申请权限
ActivityCompat.requestPermissions(MainActivity.this, permissions, 1);
} else {
// 权限已经满足,调用函数
requestLocation();
}
}
/**
* <p>描述: <p>
*
* @param
* @return
* @description:用于调用位置定位函数
* @author chenzi
* @CreateDate 2021/9/25 20:12
* @update [序号][日期YYYY-MM-DD][更改人姓名][变更描述]
*/
private void requestLocation() {
// 用于重复刷新定位
initLocation();
mLocationClient.start();
}
/**
* @description:用于刷新位置,间隔为5秒
*/
private void initLocation() {
LocationClientOption option = new LocationClientOption();
// 5000表示: 每5秒更新一次位置
option.setScanSpan(5000);
// 是否需要详细的位置信息
option.setIsNeedAddress(true);
// 设置定位模式:Hight_Accuracy Battery_Saving Device_Sensors
option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
mLocationClient.setLocOption(option);
}
/**
* <p>描述: <p>
*
* @param
* @return
* @description: onResume() onPause() onDestroy() 用于活动的暂停等等,以保证资源的即时释放
* @author chenzi
* @CreateDate 2021/9/25 21:04
* @update [序号][日期YYYY-MM-DD][更改人姓名][变更描述]
*/
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onDestroy() {
super.onDestroy();
mLocationClient.stop();
mapView.onDestroy();
// 显示小图标规定
baiduMap.setMyLocationEnabled(false);
}
/**
* <p>描述: <p>
*
* @param
* @return
* @description: 权限处理函数,判断用户是否授权相关权限
* @author chenzi
* @CreateDate 2021/9/25 20:15
* @update [序号][日期YYYY-MM-DD][更改人姓名][变更描述]
*/
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case 1: {
if (grantResults.length > 0) {
for (int result : grantResults) {
if (result != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(MainActivity.this, "您必须授权所有相关权限才可以使用", Toast.LENGTH_SHORT).show();
finish();
return;
}
}
// 调用方法函数启动定位
requestLocation();
} else {
Toast.makeText(this, "发生未知错误!", Toast.LENGTH_SHORT).show();
finish();
}
break;
}
default: {
break;
}
}
}
/**
*<p>描述: <p>
*@description: 用户图形地图点为到当前位置,其中,isFirstLocation默认为true ,符合规范
*@param bdLocation
*@return
*@author chenzi
*@CreateDate 2021/9/25 21:17
*@update [序号][日期YYYY-MM-DD][更改人姓名][变更描述]
*/
private void navigateTo(BDLocation bdLocation){
if (isFirstLocation){
LatLng lng = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());
MapStatusUpdate update = MapStatusUpdateFactory.newLatLng(lng);
baiduMap.animateMapStatus(update);
update = MapStatusUpdateFactory.zoomTo(17f);
baiduMap.animateMapStatus(update);
isFirstLocation = false;
}
// 用于显示位置小图标
MyLocationData.Builder locationBuilder = new MyLocationData.Builder();
// 获取经纬度
locationBuilder.latitude(bdLocation.getLatitude());
locationBuilder.latitude(bdLocation.getLongitude());
// 生成实例
MyLocationData locationData = locationBuilder.build();
// 显示
baiduMap.setMyLocationData(locationData);
}
/**
* <p>描述: <p>
*
* @param
* @author chenzi
* @description:位置信息的确定和显示,xxx市xxx区xxx街区...
* @return
* @CreateDate 2021/9/25 20:16
* @update [序号][日期YYYY-MM-DD][更改人姓名][变更描述]
*/
private class MyLocationListener extends BDAbstractLocationListener implements BDLocationListener {
@Override
public void onReceiveLocation(BDLocation bdLocation) {
if (bdLocation.getLocType() == BDLocation.TypeGpsLocation ||
bdLocation.getLocType() == BDLocation.TypeNetWorkLocation){
navigateTo(bdLocation);
}
/**仅仅显示位置信息,没有图形*/
用StringBuffer放位置信息
// StringBuffer currentPosition = new StringBuffer();
获取位置的方法:bdLocation的各种方法,详细见代码
// currentPosition.append("纬度:").append(bdLocation.getLatitude()).append("\n");
// currentPosition.append("经线:").append(bdLocation.getLongitude()).append("\n");
// currentPosition.append("国家:").append(bdLocation.getCountry()).append("\n");
// currentPosition.append("省:").append(bdLocation.getProvince()).append("\n");
// currentPosition.append("市:").append(bdLocation.getCity()).append("\n");
// currentPosition.append("区:").append(bdLocation.getDistrict()).append("\n");
// currentPosition.append("街道:").append(bdLocation.getStreet()).append("\n");
// currentPosition.append("详细地址:").append(bdLocation.getAddrStr()).append("\n");
// currentPosition.append("GPS:").append(bdLocation.getIndoorLocationSurpportBuidlingID());
// currentPosition.append("GPS").append(bdLocation.getTown());
// currentPosition.append("定位方式:");
判断定位的方式
// if (bdLocation.getLocType() == BDLocation.TypeGpsLocation) {
// currentPosition.append("GPS");
Toast.makeText(MainActivity.this, "GPS", Toast.LENGTH_SHORT).show();
// } else if (bdLocation.getLocType() == BDLocation.TypeNetWorkLocation) {
// currentPosition.append("网络");
Toast.makeText(MainActivity.this, "网络", Toast.LENGTH_SHORT).show();
// }
// 放入布局
// positionText.setText(currentPosition);
}
}
}
部分效果:
2021年9月25日