1. Import related dependent libraries:
implementation 'com.baidu.android:liblocation:7.3.2'
2. Create LocationClient
an instance:
LocationClient mLocationClient = new LocationClient(context);
3, set LocationClientOption
:
LocationClientOption option = new LocationClientOption();
option.setIsNeedAddress(true);// 获取详细的地址信息
option.setOpenGps(true);// 打开 GPS
option.setCoorType("bd09ll");// 设置坐标类型
option.setScanSpan(10000);// 定位间隔时间(单位:毫秒)
mLocationClient.setLocOption(option);
4, Created BDAbstractLocationListener
subclasses:
public class MyLocationListener extends BDAbstractLocationListener {
@Override
public void onReceiveLocation(BDLocation location) {
// 获取详细的地址信息
String province = location.getProvince(); // 获取省份
String city = location.getCity(); // 获取城市
String district = location.getDistrict(); // 获取区县
String street = location.getStreet(); // 获取街道信息
String address = location.getAddrStr(); // 获取详细地址信息
Log.d("location", "province: " + province + ", city: " + city + ", district: " + district + ", street: " + street + ", address: " + address);
}
}
5. Registered BDAbstractLocationListener
subclasses:
MyLocationListener myLocationListener = new MyLocationListener();
mLocationClient.registerLocationListener(myLocationListener);
6. Start positioning:
mLocationClient.start();
7. You need to add the following permissions in AndroidManifest.xml: (6.0 and above may also apply for dynamic permissions)
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
At the same time, you also need to register the application on the Baidu developer platform and obtain the AK (Access Key), and set the AK in the code: (same as step 3)
LocationClientOption option = new LocationClientOption();
option.setIsNeedAddress(true);
option.setOpenGps(true);
option.setCoorType("bd09ll");
option.setScanSpan(10000);
option.setIgnoreKillProcess(false);
option.setEnableSimulateGps(false);
option.setEnableCache(true);
option.setWifiCacheTimeOut(5 * 60 * 1000);
option.setAk("Your AK");
mLocationClient.setLocOption(option);
Attachment. Registration and obtaining key (AK):
Refer to the official document: androidsdk | Baidu Map API SDK