Android利用百度AK定位获取详细位置信息完整示例步骤

1,导入相关的依赖库:

implementation 'com.baidu.android:liblocation:7.3.2'

 2,创建 LocationClient 实例:

LocationClient mLocationClient = new LocationClient(context);

3,设置 LocationClientOption

LocationClientOption option = new LocationClientOption();
option.setIsNeedAddress(true);// 获取详细的地址信息
option.setOpenGps(true);// 打开 GPS
option.setCoorType("bd09ll");// 设置坐标类型
option.setScanSpan(10000);// 定位间隔时间(单位:毫秒)
mLocationClient.setLocOption(option);

 4,创建 BDAbstractLocationListener 的子类:

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,注册 BDAbstractLocationListener 的子类:

MyLocationListener myLocationListener = new MyLocationListener();
mLocationClient.registerLocationListener(myLocationListener);

6,启动定位:

mLocationClient.start();

7,需要在 AndroidManifest.xml 中添加如下权限:(6.0以上可能还要申请动态权限)

<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" />

 同时,还需要在百度开发者平台上注册应用并获取 AK(Access Key),在代码中设置 AK:(同第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);

附.注册及获取密钥(AK):

参考官方文档:androidsdk | 百度地图API SDK

猜你喜欢

转载自blog.csdn.net/wh445306/article/details/130184565