AndroidStudio|实现百度地图定位功能

实现功能

根据百度地图开发者文档,编写百度定位程序,在地图标出自己现在的位置。

实现代码

 MainActivity extends Activity {
    private MapView mMapView = null;
    private BaiduMap mBaiduMap;
    private LocationClient mLocationClient;
    private BitmapDescriptor mMarker;
    private boolean ifFrist = true;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mMapView = findViewById(R.id.bmapView);
        mBaiduMap = mMapView.getMap();
        mLocationClient = new LocationClient(this);
        MyLocationListener myLocationListener = new MyLocationListener();
        mLocationClient.registerLocationListener(myLocationListener);

        //用于显示当前位置
        mMarker = BitmapDescriptorFactory.fromResource(R.drawable.icon_start);
        mBaiduMap.setMyLocationEnabled(true);
        LocationClientOption option = new LocationClientOption();
   option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        // 打开定位
        option.setOpenGps(true);  
        option.setCoorType("bd09ll"); 
        option.setScanSpan(1000);
        option.setIsNeedAddress(true);
        mLocationClient.setLocOption(option);
        mLocationClient.start();
    }
 MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location == null || mMapView == null){
                return;
            }
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    .latitude(location.getLatitude())
                    .longitude(location.getLongitude())
                    .direction(location.getDirection())
                    .build();
            mBaiduMap.setMyLocationData(locData);
            MyLocationConfiguration configuration = new MyLocationConfiguration(
                    MyLocationConfiguration.LocationMode.NORMAL, false, mMarker);

            mBaiduMap.setMyLocationConfiguration(configuration);

            if (ifFrist) {
                LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(ll);
                builder.zoom(18.0f);   mBaiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
                ifFrist = false;
            }
        }
    }
}

你可能感兴趣的:(学习笔记)