Android primary Baidu map (3) direction sensor positioning function

1. Add positioning permissions to the AndroidManifest.xml file:





2, create a sensor class, the code is as follows

package com.example.baidumap;

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

public class MyOrientationListener implements SensorEventListener {

    private SensorManager mSensorManager;
    private Context mContext;
    private Sensor mSensor;
    private float lastX;

    public MyOrientationListener(Context context){
        this.mContext = context;
    }

    @SuppressWarnings("deprecation")
    public void start(){
        mSensorManager = (SensorManager) mContext
                .getSystemService(Context.SENSOR_SERVICE);
        if (mSensorManager != null){
            // get direction sensor
            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){
        // TODO Auto-generated method stub
    }

    @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);
    }
}

3. Add a positioning button to the layout file

< div class="Highlighter">

4. Add resource files (the original location of the picture is in my Baidu cloud disk (extract code: k5b7) In the compressed package assets, take them and put them in the following files respectively)

Share pictures

5. MainActivity code (note: MainActivity inherits iew.OnClickListener interface)

package com.example.baidumap;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.CoordType;
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;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private Context context;
    private MapView mapView = null;
    private BaiduMap baiduMap = null;

    //Positioning related
    private double mLatitude;
    private double mLongtitude;

    private MyOrientationListener myOrientationListener; //Orientation sensor
    private float mCurrentx;

    //Custom icon
    private BitmapDescriptor mIconLocation;
    private LocationClient mLocationClient;
    public BDAbstractLocationListener myListener;
    private LatLng mLastLocationData;
    private boolean isFirstin = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.activity_main);
        SDKInitializer.setCoordType(CoordType.BD09LL);
        this.context = this;

        mapView = (MapView)findViewById(R.id.baiduMapView);
        baiduMap = mapView.getMap(); //Get map control reference

        initLocation();
        button();
    }

    @Override
    protected void onStart() {
        super.onStart();
        baiduMap.setMyLocationEnabled(true); //Enable positioning
        if (!mLocationClient.isStarted())mLocationClient.start();
        myOrientationListener.start(); //Turn on the orientation sensor
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }
    @Override
    protected void onStop() {
        super.onStop();
        baiduMap.setMyLocationEnabled(false); //Stop positioning
        mLocationClient.stop();
        myOrientationListener.stop(); //Stop the orientation sensor
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        baiduMap.setMyLocationEnabled(false);
        mapView.onDestroy();
        mapView = null;
    }

    @Override
    public void onClick(View view) {
        SDKInitializer.initialize(getApplicationContext());
        switch (view.getId()) {
            case R.id.btn_Location: {
                centerToMyLocation(mLatitude, mLongtitude);
                break;
            }
        }
    }

    //Button response
    private void button() {
        Button btn_lco = (Button) findViewById(R.id.btn_Location); //Button
        btn_lco.setOnClickListener(this); //Button processing
    }

    //position
    private class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            //mapView is not processing the newly received position after being destroyed
            if (location == null || mapView == null){
                return;
            }
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // Set the direction information obtained by the developer here, clockwise 0-360
                    .direction(mCurrentx).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            baiduMap.setMyLocationData(locData);
            //Set custom icon
            MyLocationConfiguration config = new MyLocationConfiguration(MyLocationConfiguration.LocationMode.NORMAL, true, mIconLocation);
            baiduMap.setMyLocationConfiguration(config);
            //Update the latitude and longitude
            mLatitude = location.getLatitude();
            mLongtitude = location.getLongitude();
            //Set the starting point
            mLastLocationData = new LatLng(mLatitude, mLongtitude);
            if (isFirstin) {
                centerToMyLocation(location.getLatitude(), location.getLongitude());
                if (location.getLocType() == BDLocation.TypeGpsLocation) {
                    // GPS positioning results
                    Toast.makeText(context, "Location:"+location.getAddrStr(), Toast.LENGTH_SHORT).show();
                } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
                    // Network positioning results
                    Toast.makeText(context, "Location:"+location.getAddrStr(), Toast.LENGTH_SHORT).show();
                } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {
                    // Offline positioning result
                    Toast.makeText(context, "Location:"+location.getAddrStr(), Toast.LENGTH_SHORT).show();
                } else if (location.getLocType() == BDLocation.TypeServerError) {
                    Toast.makeText(context, "Locating: Server Error", Toast.LENGTH_SHORT).show();
                } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
                    Toast.makeText(context, "Locating: Network Error", Toast.LENGTH_SHORT).show();
                } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
                    Toast.makeText(context, "Positioning: The phone mode is wrong, please check if you are flying", Toast.LENGTH_SHORT).show();
                }
                isFirstin = false;
            }
        }
    }
    //Initialize positioning
    private void initLocation() {
        //Zoom the map
        MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(15.0f);
        baiduMap.setMapStatus(msu);
        //Turn on positioning
        baiduMap.setMyLocationEnabled(true);
        //Declare the LocationClient class
        mLocationClient = new LocationClient(this);
        //Set LocationClient related parameters through LocationClientOption
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // Open gps
        option.setCoorType("bd09ll"); // Set the coordinate type
        option.setIsNeedAddress(true);//Set whether address information is required
        option.setScanSpan(1000);
        //Set locationClientOption
        mLocationClient.setLocOption(option);
        myListener = new MyLocationListener();
        //Register the listener function
        mLocationClient.registerLocationListener(myListener);
        //Initialize icon
        mIconLocation = BitmapDescriptorFactory.fromResource(R.drawable.navi_map_gps);
        initOrientation();
        //Start positioning
        mLocationClient.start();
    }
    //Back to the positioning center
    private void centerToMyLocation(double latitude, double longtitude) {
        baiduMap.clear();
        mLastLocationData = new LatLng(latitude, longtitude);
        MapStatusUpdate msu = MapStatusUpdateFactory.newLatLng(mLastLocationData);
        baiduMap.animateMapStatus(msu);
    }
    //sensor
    private void initOrientation() {
        //sensor
        myOrientationListener = new MyOrientationListener(context);
        myOrientationListener.setOnOrientationListener(new MyOrientationListener.OnOrientationListener() {
            @Override
            public void onOrientationChanged(float x) {
                mCurrentx = x;
            }
        });
    }
}

6. Start the project

share picture

7. Attach the items of this chapter (extract code: jl2v).





package com.example.baidumap;

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

public class MyOrientationListener implements SensorEventListener {

    private SensorManager mSensorManager;
    private Context mContext;
    private Sensor mSensor;
    private float lastX;

    public MyOrientationListener(Context context){
        this.mContext = context;
    }

    @SuppressWarnings("deprecation")
    public void start(){
        mSensorManager = (SensorManager) mContext
                .getSystemService(Context.SENSOR_SERVICE);
        if (mSensorManager != null){
            // get direction sensor
            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){
        // TODO Auto-generated method stub
    }

    @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);
    }
}

package com.example.baidumap;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.CoordType;
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;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private Context context;
    private MapView mapView = null;
    private BaiduMap baiduMap = null;

    //Positioning related
    private double mLatitude;
    private double mLongtitude;

    private MyOrientationListener myOrientationListener; //Orientation sensor
    private float mCurrentx;

    //Custom icon
    private BitmapDescriptor mIconLocation;
    private LocationClient mLocationClient;
    public BDAbstractLocationListener myListener;
    private LatLng mLastLocationData;
    private boolean isFirstin = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.activity_main);
        SDKInitializer.setCoordType(CoordType.BD09LL);
        this.context = this;

        mapView = (MapView)findViewById(R.id.baiduMapView);
        baiduMap = mapView.getMap(); //Get map control reference

        initLocation();
        button();
    }

    @Override
    protected void onStart() {
        super.onStart();
        baiduMap.setMyLocationEnabled(true); //Enable positioning
        if (!mLocationClient.isStarted())mLocationClient.start();
        myOrientationListener.start(); //Turn on the orientation sensor
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }
    @Override
    protected void onStop() {
        super.onStop();
        baiduMap.setMyLocationEnabled(false); //Stop positioning
        mLocationClient.stop();
        myOrientationListener.stop(); //Stop the orientation sensor
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        baiduMap.setMyLocationEnabled(false);
        mapView.onDestroy();
        mapView = null;
    }

    @Override
    public void onClick(View view) {
        SDKInitializer.initialize(getApplicationContext());
        switch (view.getId()) {
            case R.id.btn_Location: {
                centerToMyLocation(mLatitude, mLongtitude);
                break;
            }
        }
    }

    //Button response
    private void button() {
        Button btn_lco = (Button) findViewById(R.id.btn_Location); //Button
        btn_lco.setOnClickListener(this); //Button processing
    }

    //position
    private class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            //mapView is not processing the newly received position after being destroyed
            if (location == null || mapView == null){
                return;
            }
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // Set the direction information obtained by the developer here, clockwise 0-360
                    .direction(mCurrentx).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            baiduMap.setMyLocationData(locData);
            //Set custom icon
            MyLocationConfiguration config = new MyLocationConfiguration(MyLocationConfiguration.LocationMode.NORMAL, true, mIconLocation);
            baiduMap.setMyLocationConfiguration(config);
            //Update the latitude and longitude
            mLatitude = location.getLatitude();
            mLongtitude = location.getLongitude();
            //Set the starting point
            mLastLocationData = new LatLng(mLatitude, mLongtitude);
            if (isFirstin) {
                centerToMyLocation(location.getLatitude(), location.getLongitude());
                if (location.getLocType() == BDLocation.TypeGpsLocation) {
                    // GPS positioning results
                    Toast.makeText(context, "Location:"+location.getAddrStr(), Toast.LENGTH_SHORT).show();
                } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
                    // Network positioning results
                    Toast.makeText(context, "Location:"+location.getAddrStr(), Toast.LENGTH_SHORT).show();
                } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {
                    // Offline positioning result
                    Toast.makeText(context, "Location:"+location.getAddrStr(), Toast.LENGTH_SHORT).show();
                } else if (location.getLocType() == BDLocation.TypeServerError) {
                    Toast.makeText(context, "Locating: Server Error", Toast.LENGTH_SHORT).show();
                } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
                    Toast.makeText(context, "Locating: Network Error", Toast.LENGTH_SHORT).show();
                } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
                    Toast.makeText(context, "Positioning: The phone mode is wrong, please check if you are flying", Toast.LENGTH_SHORT).show();
                }
                isFirstin = false;
            }
        }
    }
    //Initialize positioning
    private void initLocation() {
        //Zoom the map
        MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(15.0f);
        baiduMap.setMapStatus(msu);
        //Turn on positioning
        baiduMap.setMyLocationEnabled(true);
        //Declare the LocationClient class
        mLocationClient = new LocationClient(this);
        //Set LocationClient related parameters through LocationClientOption
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // Open gps
        option.setCoorType("bd09ll"); // Set the coordinate type
        option.setIsNeedAddress(true);//Set whether address information is required
        option.setScanSpan(1000);
        //Set locationClientOption
        mLocationClient.setLocOption(option);
        myListener = new MyLocationListener();
        //Register the listener function
        mLocationClient.registerLocationListener(myListener);
        //Initialize icon
        mIconLocation = BitmapDescriptorFactory.fromResource(R.drawable.navi_map_gps);
        initOrientation();
        //Start positioning
        mLocationClient.start();
    }
    //Back to the positioning center
    private void centerToMyLocation(double latitude, double longtitude) {
        baiduMap.clear();
        mLastLocationData = new LatLng(latitude, longtitude);
        MapStatusUpdate msu = MapStatusUpdateFactory.newLatLng(mLastLocationData);
        baiduMap.animateMapStatus(msu);
    }
    //sensor
    private void initOrientation() {
        //sensor
        myOrientationListener = new MyOrientationListener(context);
        myOrientationListener.setOnOrientationListener(new MyOrientationListener.OnOrientationListener() {
            @Override
            public void onOrientationChanged(float x) {
                mCurrentx = x;
            }
        });
    }
}

WordPress database error: [Table 'yf99682.wp_s6mz6tyggq_comments' doesn't exist]
SELECT SQL_CALC_FOUND_ROWS wp_s6mz6tyggq_comments.comment_ID FROM wp_s6mz6tyggq_comments WHERE ( comment_approved = '1' ) AND comment_post_ID = 3615 ORDER BY wp_s6mz6tyggq_comments.comment_date_gmt ASC, wp_s6mz6tyggq_comments.comment_ID ASC

Leave a Comment

Your email address will not be published.