Map my location in real time

Keywords: Mobile Android SDK

First, you need to display the map. Please see another article of mine

Android uses Baidu map API to display maps

Then get the longitude and latitude in the positioning information in real time,

Android gets LocationProvider and location information

Then activate the positioning function to mark my position

  • Turn on location layer setMyLocationEnabled(true)
  • Construct location data MyLocationData object
  • Set positioning data and configure information for positioning layers
  • Turn off locating layer setMyLocationEnabled(false)

The code in Activity is as follows:

    private MapView mMapView;
    public final static String TAG = "Location";
    private BaiduMap mBaiduMap;  //Define Baidu map object
    //Record whether to locate for the first time, and then set the logic in the locationUpdates() method
    private boolean isFirstLoc = true;
    //Current positioning mode
    private MyLocationConfiguration.LocationMode locationMode;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //Initialize the map SDK,
        //It needs to be on the setcontentview (r.layout. Activity > main); and
        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.activity_main);
        initMap();   //Initialize map
        locationProvice();//Location service



    }

    private void initMap() {
        //Get map control reference
        mMapView = findViewById(R.id.bmapView);
        mBaiduMap = mMapView.getMap(); //Get Baidu map object
    }

    /**
     *  Initialize the location service to get the current location
     */
    private void locationProvice() {
        //Get location service
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        //Get the best LocationProvider
        //Create a filter object
        //You need to add permission < uses permission Android: name = "Android. Permission. Access" fine "location" / >
        Criteria criteria = new Criteria();
        //Set to free
        criteria.setCostAllowed(false);
        //The most accurate
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        //Set medium power consumption
        criteria.setPowerRequirement(Criteria.POWER_MEDIUM);



        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }

        locationManager.requestLocationUpdates(
                LocationManager.NETWORK_PROVIDER,   //Specify location provider
                1000,                 //Interval time
                1,                 //Location interval 1 meter
                new LocationListener() {//Monitor whether GPS positioning information changes
                    @Override
                    public void onLocationChanged(Location location) {
                        //When GPS information changes, callback
                        locationUpdates(location);
                    }

                    @Override
                    public void onStatusChanged(String provider, int status, Bundle extras) {
                        //When GPS status changes, callback
                    }

                    @Override
                    public void onProviderEnabled(String provider) {
                        //Location provider start callback
                    }

                    @Override
                    public void onProviderDisabled(String provider) {
                        //Callback on location provider shutdown
                    }
                }
        );
        //Get the latest location information
        Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        //Pass the latest location information to the locationUpdates() method
        locationUpdates(location);
    }


    public void locationUpdates(Location location) {
        if (location != null) {
            LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
            //Create a string builder to record location information
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("Your location is: \n");
            stringBuilder.append("longitude: ");
            stringBuilder.append(location.getLongitude());
            stringBuilder.append("\n latitude:");
            stringBuilder.append(location.getLatitude());
            Log.i(TAG, stringBuilder.toString());

            if (isFirstLoc) {
                //Update coordinate position
                MapStatusUpdate update = MapStatusUpdateFactory.newLatLng(ll);
                //Set map location
                mBaiduMap.animateMapStatus(update);
                isFirstLoc=false;
            }
            //Construct location data
            MyLocationData locationData = new MyLocationData.Builder()
                    .accuracy(location.getAccuracy()) //Setting accuracy
                    .direction(0)            //Set direction information
                    .latitude(location.getLatitude()) //Set latitude coordinates
                    .longitude(location.getLongitude()) //Set latitude coordinates
                    .build();
            mBaiduMap.setMyLocationData(locationData);
            //Set custom icon
            BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromResource(R.drawable.icon_geo);
            //Set positioning mode
            locationMode = MyLocationConfiguration.LocationMode.NORMAL;
            //Set construction method
            MyLocationConfiguration configuration = new MyLocationConfiguration(
                    locationMode,true,bitmapDescriptor
            );
            //Show positioning icons
            mBaiduMap.setMyLocationConfiguration(configuration);
            //Then add the onStart() method and onStop
            //Turn on positioning layer
            //mBaiduMap.setMyLocationEnabled(true);
            //Stop locating layers
            // mBaiduMap.setMyLocationEnabled(false);
        } else {
           Log.i(TAG ,"No location information obtained");
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        //Turn on positioning layer
        mBaiduMap.setMyLocationEnabled(true);
    }

    @Override
    protected void onStop() {
        super.onStop();
        mBaiduMap.setMyLocationEnabled(false);
    }

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

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

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
        mMapView = null;
    }

Posted by evaoparah on Sun, 08 Dec 2019 22:15:40 -0800