首先獲取定位權限,集成百度地圖
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(); //獲取街道信息 } }