学习百度地图API的定位

最近学习了一下百度地图api的定位+方向传感器,做一下简单总结,不闲聊~ 上代码!就是这么干脆 0.0

LocationActivity.java代码:

package com.example.lenovo.baidumap;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;

/** * Created by shan on 2016/6/20. */
public class LocationActivity extends Activity implements BDLocationListener{
    private MapView mapView;
    private BaiduMap mBaiduMap;
    private LocationClient mLocClient;//定位端
    private boolean isFirstIn = true;//是否是第一次定位
    private LatLng latLng;//经纬度
    private OrientationListener orientationListener;//方向传感器
    private float mCurrentX;//当前方向指示
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //在使用SDK各组件之前初始化context信息,传入ApplicationContext
        //注意:该方法要在setContentView方法之前
        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.location);
        initView();
    }

    /** * 初始化view */
    private void initView() {
        mapView = (MapView) findViewById(R.id.baidumap);
        mBaiduMap = mapView.getMap();
        //设置地图放大比例(100米范围)
        mBaiduMap.setMapStatus(MapStatusUpdateFactory.zoomTo(17.5f));
        //开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        //自定义定位图标
        BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.mipmap.icon_fangxiang);
        //LocationMode分三种模式:罗盘模式,跟随模式,正常模式。这里设置为正常模式
        MyLocationConfiguration config = new MyLocationConfiguration(MyLocationConfiguration.LocationMode.NORMAL,
                true,bitmap);
        mBaiduMap.setMyLocationConfigeration(config);
        mLocClient = new LocationClient(this);
        mLocClient.registerLocationListener(this);
        LocationClientOption option = new LocationClientOption();
        //经纬度坐标格式:bd09ll
        option.setCoorType("bd09ll");
        //要想获取定位信息就必须设置为true
        option.setIsNeedAddress(true);
        //设置语义化位置信息,用bdLocation.getLocationDescribe()得到位置信息,如:"在XXX附近"
        option.setIsNeedLocationDescribe(true);
        //打开gps进行定位
        option.setOpenGps(true);
        //扫描间隔为1秒
        option.setScanSpan(1000);
        //设置LocationClientOption
        mLocClient.setLocOption(option);
        //实例化方向传感监听器并设置监听
        orientationListener = new MyOrientationListener(this);
        orientationListener.setOnOrientationListener(new MyOrientationListener.OnOrientationListener() {
            @Override
            public void onOrientationChanged(float x) {
                mCurrentX = x;
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        //开启定位
        mLocClient.start();
        //开启方向传感器
        orientationListener.start();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();

    }

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

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        //关闭定位
        mLocClient.stop();
        //关闭方向传感器
        orientationListener.stop();
        //关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
    }

    /** * 定位监听 */
    @Override
    public void onReceiveLocation(BDLocation bdLocation) {
        //如果bdLocation为空或mapView销毁后不再处理新数据接收的位置
        if (bdLocation == null || mBaiduMap == null) {
            return;
        }
        //定位数据
        MyLocationData data = new MyLocationData.Builder()
                .direction(mCurrentX)//设置方向传感器的指示方向随着mCurrentX变化而变化
                .accuracy(0)//设置定位精度bdLocation.getRadius(),如果为0,外面的圆圈消失
                .latitude(bdLocation.getLatitude())
                .longitude(bdLocation.getLongitude())
                .build();
        //设置定位数据
        mBaiduMap.setMyLocationData(data);
        //判断是否是第一次定位
        if (isFirstIn) {
            //当移动到别的位置需要重新返回到当前位置时,抽取下面3行代码即可
            latLng= new LatLng(bdLocation.getLatitude(),bdLocation.getLongitude());
            MapStatusUpdate msu = MapStatusUpdateFactory.newLatLng(latLng);
            mBaiduMap.animateMapStatus(msu);
            isFirstIn = false;
            //吐司显示一下当前位置信息,这里我设置显示的语义化信息
            Toast.makeText(LocationActivity.this, bdLocation.getLocationDescribe(), Toast.LENGTH_SHORT).show();
        }
    }

    /** * 返回键退出 */
    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }
}

location的xml代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent">
    <com.baidu.mapapi.map.MapView  android:id="@+id/baidumap" android:layout_width="match_parent" android:layout_height="match_parent">
    </com.baidu.mapapi.map.MapView>
</LinearLayout>

方向传感器OrientationListener.java代码:

package com.example.lenovo.baidumap;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

public class OrientationListener implements SensorEventListener{
    private SensorManager mSensorManager;
    private Context mContext;
    private Sensor mSensor;
    private float lastX;
    public OrientationListener(Context context){
        this.mContext = context;
    }

    /** * 开始监听 */
    @SuppressWarnings({ "deprecation" })
    public void start(){
        mSensorManager = (SensorManager) mContext.getSystemService(Context.SENSOR_SERVICE);
        if (mSensorManager != null){
            //获得方向传感器
            mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
        }
        if (mSensor != null){
            mSensorManager.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_UI);
        }
    }

    /** * 结束监听 */
    public void stop(){
        mSensorManager.unregisterListener(this);
    }

    @Override
    public void onAccuracyChanged(Sensor arg0, int arg1){

    }

    @SuppressWarnings({ "deprecation" })
    @Override
    public void onSensorChanged(SensorEvent event){
        if (event.sensor.getType() == Sensor.TYPE_ORIENTATION){
            float x = event.values[SensorManager.DATA_X];
            if (Math.abs(x - lastX) > 1.0){
                if (mOnOrientationListener != null){
                    mOnOrientationListener.onOrientationChanged(x);
                }
            }
            lastX = x;
        }
    }

    private OnOrientationListener mOnOrientationListener;
    public void setOnOrientationListener(OnOrientationListener mOnOrientationListener){
        this.mOnOrientationListener = mOnOrientationListener;
    }

    public interface OnOrientationListener{
        void onOrientationChanged(float x);
    }
}

over~~欢迎批评指正~~

你可能感兴趣的:(学习百度地图API的定位)