首先获取定位权限,集成百度地图
if (ContextCompat.checkSelfPermission(NewWaiChuDetialActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {//未开启定位权限 //开启定位权限,200是标识码 ActivityCompat.requestPermissions(NewWaiChuDetialActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 200); } else { Toast.makeText(NewWaiChuDetialActivity.this, "已开启定位权限", Toast.LENGTH_LONG).show(); }
回调
@Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode) { case 200://刚才的识别码 if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {//用户同意权限,执行我们的操作 //开始定位,下面的操作 } else {//用户拒绝之后,当然我们也可以弹出一个窗口,直接跳转到系统设置页面 Toast.makeText(NewWaiChuDetialActivity.this, "未开启定位权限,请手动到设置去开启权限", Toast.LENGTH_LONG).show(); } break; default: break; } }
集成百度地图
implementation files('libs/BaiduLBS_Android.jar')
<!-- 定位 --> <service android:name="com.baidu.location.f" android:enabled="true" android:process=":remote" /> <meta-data android:name="com.baidu.lbsapi.API_KEY" android:value="百度地图的value" /> <!-- 定位END -->
上代码!!!
//定位服务的客户端。宿主程序在客户端声明此类,并调用,目前只支持在主线程中启动 locationClient = new LocationClient(getApplicationContext()); //声明LocationClient类实例并配置定位参数 LocationClientOption locationOption = new LocationClientOption(); MyLocationListener myLocationListener = new MyLocationListener(); //注册监听函数 locationClient.registerLocationListener(myLocationListener); locationOption.setScanSpan(0); //可选,是否需要地址信息,默认为不需要,即参数为false locationOption.setIsNeedAddress(true); locationOption.setOpenGps(true); // 打开gps //option.setAddrType("all");//返回的定位结果包含地址信息 locationOption.setCoorType("gcj02"); // 设置坐标类型 locationClient.setLocOption(locationOption); //开启定位 locationClient.start();
public class MyLocationListener implements BDLocationListener { @Override public void onReceiveLocation(BDLocation location) { //此处的BDLocation为定位结果信息类,通过它的各种get方法可获取定位相关的全部结果 //以下只列举部分获取地址相关的结果信息 //更多结果信息获取说明,请参照类参考中BDLocation类中的说明 //int locType = location.getLocType(); //获取详细地址信息 addr = location.getAddrStr(); waichuDingwei.setText(addr); //String country = location.getCountry(); //获取国家 //String province = location.getProvince(); //获取省份 //String city = location.getCity(); //获取城市 //String district = location.getDistrict(); //获取区县 //String street = location.getStreet(); //获取街道信息 } }