Android——定位服务(百度地图)

第一步:在清单文件中申请权限,如下:

    
    
    
    
    
    
    
    
    
    

然后将自己创建应用申请到的ak密钥添加到value中,android:name是固定的

 

在添加一个LDB SDK服务(内容固定不变)

 

两种方式显示定位信息
第一种:经纬度,和省市区等详细位置(定位方式必须是网络定位才能显示详细位置信息)
第二种:图型形式
Android——定位服务(百度地图)_第1张图片
activity_main.xml代码如下:



    
    
    

MainActivity.java代码如下:

public class MainActivity extends AppCompatActivity {
    private MapView BaiduMap;
    private LocationClient Client;
    private TextView Position;
    private BaiduMap baiduMap;//地图总控制器
    private boolean isFirstLocate = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //一定要在setContentView()前调用
        SDKInitializer.initialize(getApplicationContext());
        Client = new LocationClient(getApplicationContext());//获取全局Context
        Client.registerLocationListener(new MyLocationListener());//注册一个定位监听器,获取位置信息,回调此定位监听器

        setContentView(R.layout.activity_main);
        BaiduMap = (MapView) findViewById(R.id.baiduMap);
        Position = (TextView) findViewById(R.id.position);
        List PermissionList = new ArrayList<>();
        baiduMap = BaiduMap.getMap();//获取实例,可以对地图进行一系列操作,比如:缩放范围,移动地图
        baiduMap.setMyLocationEnabled(true);//允许当前设备显示在地图上
        //判断权限是否授权
        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()){
            String[] Permissions = PermissionList.toArray(new String[PermissionList.size()]);//转化为数组
            ActivityCompat.requestPermissions(MainActivity.this,Permissions,1);//一次性申请权限
        }else {
            requestLocation();
        }
    }
    private void navigateTo(BDLocation location){
        if (isFirstLocate){
            LatLng lng = new LatLng(location.getLatitude(),location.getLongitude());//指定经纬度
            MapStatusUpdate update = MapStatusUpdateFactory.newLatLng(lng);
            baiduMap.animateMapStatus(update);
            update = MapStatusUpdateFactory.zoomTo(16f);//百度地图缩放级别限定在3-19
            baiduMap.animateMapStatus(update);
            isFirstLocate = false;
        }
        MyLocationData.Builder builder = new MyLocationData.Builder();
        builder.latitude(location.getLatitude());
        builder.longitude(location.getLongitude());
        MyLocationData locationData = builder.build();
        baiduMap.setMyLocationData(locationData);
    }
    private void requestLocation(){
        InitLocation();
        Client.start();
    }
    /*
    * LBS SKD定位模式
    * 1:Hight_Accuracy:高精确模式,优先使用GPS定位,其次使用网络定位
    * 2:Battery_Saving:节电模式,使用网络定位
    * 3:Device_Sensors:传感器模式,使用GPS
    * */
    private void InitLocation(){
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);//高精确模式
        option.setScanSpan(5000);//ms
        option.setIsNeedAddress(true);//获取详细信息许可
        Client.setLocOption(option);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Client.stop();
        BaiduMap.onDestroy();
        baiduMap.setMyLocationEnabled(false);
    }

    @Override
    protected void onResume() {
        super.onResume();
        BaiduMap.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        BaiduMap.onPause();
    }

    @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(this,"必须同意所有权限才能使用本程序",Toast.LENGTH_SHORT).show();
                            finish();
                            return;
                        }
                    }
                    requestLocation();
                }else {
                    Toast.makeText(this,"发生未知错误",Toast.LENGTH_SHORT).show();
                    finish();
                }
                break;
                default:
        }
    }

    public class MyLocationListener implements BDLocationListener{

        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            if (bdLocation.getLocType() == BDLocation.TypeGpsLocation || bdLocation.getLocType() == BDLocation.TypeNetWorkLocation){
                navigateTo(bdLocation);
            }
            StringBuilder currentPosition = new StringBuilder();
            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("定位方式:");
            if (bdLocation.getLocType() == BDLocation.TypeGpsLocation){
                currentPosition.append("GPS");
            }else if (bdLocation.getLocType() == BDLocation.TypeNetWorkLocation){
                currentPosition.append("网络");
            }
            Position.setText(currentPosition);
        }
    }
}

你可能感兴趣的:(Android,Studio,定位,百度,android,java,android,studio)