Using Baidu map open source code to realize positioning and real-time path tracking

First demonstrate the effect: (the video can't be played, and the pictures make up the number)


Ideas and steps of real-time path:
Idea: if you need to realize real-time tracking on the map, you first need to realize the positioning function. On the basis of realizing the positioning function, you need to draw the walking track on the map, so how to draw the walking track? It is necessary to record the longitude and latitude of walking in real time. Draw a straight line between two points. If the positioning frequency is high in the middle, the more longitude and latitude will be recorded, so that the recorded walking path can be smoother.
If the playback function is required, a database needs to be established to store the traveling line. The database should have the relationship between a line and multiple points, so two tables are required. One table is the recorded line and the other table is the multiple points corresponding to a recorded line. (I haven't realized the playback function yet)

Add permissions and keys first, and modify the manifest XML file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.map_track"
    android:versionCode="1"
    android:versionName="1.0">

    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.USE_CREDENTIALS" />
    <uses-permission android:name="android.permission.MANAGE_ACCOUNTS" />
    <uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS" />
    <uses-permission android:name="com.android.launcher.permission.READ_SETTINGS" />
    <uses-permission android:name="android.permission.BROADCAST_STICKY" />
    <uses-permission android:name="android.permission.WRITE_SETTINGS" />
    <!-- This permission is used for network location-->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
    <!-- This permission is used to access GPS location-->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
    <!-- For access wifi Network information, wifi The information will be used for network positioning-->
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
    <!--  Obtain operator information to support the provision of interfaces related to operator information  -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" ></uses-permission>
    <!-- This permission is used to get wifi Access to, wifi Information will be used for network positioning-->
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
    <!--  Used to read the current status of the phone  -->
    <uses-permission android:name="android.permission.READ_PHONE_STATE" ></uses-permission>
    <!-- Write external storage. If the developer uses an offline map and the data is written in the external storage area, you need to apply for this permission -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" ></uses-permission>
    <!-- Access the network and request map related business data, including map data, route planning, POI Search, etc -->
    <uses-permission android:name="android.permission.INTERNET" ></uses-permission>
    <!--  SD Card read permission, user writes offline positioning data  -->
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"></uses-permission>
    <!--  Allow applications to read low-level system log files-->
    <uses-permission android:name="android.permission.READ_LOGS"></uses-permission>
    <!-- Read external storage. If developers use so Dynamic loading function and so If the file is placed in the external storage area, you need to apply for the permission, otherwise you don't need it -->
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"  />

    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
    
    <application

        android:allowBackup="true"
        android:icon="@drawable/ic_launcher_background"
        android:label="Line tracking case"
        android:theme="@style/AppTheme" >

        <meta-data
            android:name="com.baidu.lbsapi.API_KEY"
            android:value="Dt7DLSza4fP0NBGMEMjF2IRNaOtXqqn6" ></meta-data>

        <activity
            android:name="com.example.map_track.MainActivity"
            android:label="Line tracking case" >

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service android:name="com.baidu.location.f"
            android:enabled="true"
            android:process=":remote"> </service>

    </application>

</manifest>

Then set the activity of the layout file_ main. XML file

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="16dp"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="16dp"
    tools:context=".MainActivity">

    <!--
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    -->


    <com.baidu.mapapi.map.MapView
        android:id="@+id/bmapView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clickable="true" />

</RelativeLayout>

(the following classes are completed in the app/java/com.example.map_track package)

First, a line class Track should be established to store the information of each line;

package com.example.map_track;

import java.util.ArrayList;

/**
 *Line tracking object
 **/

public class Track {    //line
    private int id;
    private String track_name;
    private String create_date;
    private String start_loc;
    private String end_loc;
    private ArrayList<TrackDetail> trackDetails;

    public ArrayList<TrackDetail> getTrackDetails() {
        return trackDetails;
    }
    public void setTrackDetails(ArrayList<TrackDetail> trackDetails) {
        this.trackDetails = trackDetails;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getTrack_name() {
        return track_name;
    }
    public void setTrack_name(String track_name) {
        this.track_name = track_name;
    }
    public String getCreate_date() {
        return create_date;
    }
    public void setCreate_date(String create_date) {
        this.create_date = create_date;
    }
    public String getStart_loc() {
        return start_loc;
    }
    public void setStart_loc(String start_loc) {
        this.start_loc = start_loc;
    }
    public  String getEnd_loc() {
        return end_loc;
    }
    public  void setEnd_loc(String end_loc) {
        this.end_loc = end_loc;
    }
    public Track(int id, String track_name, String create_date,String start_loc, String end_loc) {
        super();
        this.id = id;
        this.track_name = track_name;
        this.create_date = create_date;
        this.start_loc = start_loc;
        this.end_loc = end_loc;
    }

    public Track(String track_name, String create_date, String start_loc, String end_loc) {
        super();
        this.track_name = track_name;
        this.create_date = create_date;
        this.start_loc = start_loc;
        this.end_loc = end_loc;
    }

    public Track() {
        super();
    }
}

After the route class Track is established, a route node class TrackDetail needs to be established to store the information of each point on the route;

package com.example.map_track;

public class  TrackDetail {
    private int id;
    private double lat;
    private double lng;
    private Track track;
    public int getId() {
        return id;
    }
    public void setId(int id) { this.id = id; }
    public double getLat() {
        return lat;
    }
    public void setLat(double lat) {
        this.lat = lat;
    }
    public double getLng() {
        return lng;
    }
    public void setLng(double lng) {
        this.lng = lng;
    }
    public Track getTrack() {
        return track;
    }
    public void setTrack(Track track) {
        this.track = track;
    }
    public TrackDetail(int id, double lat, double lng) {
        super();
        this.id = id;
        this.lat = lat;
        this.lng = lng;
    }
}

You also need to set up a database assistant class DatabaseHelper:

package com.example.map_track;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 Data assistant class
 **/
public class DatabaseHelper extends SQLiteOpenHelper {

    private  static String DB_NAME = "track.db";
    //Table name
    public  static String TABLE_TRACK = "track";
    public static String TABLE_TRACK_DETAIL = "track_detail";

    //field
    public static String ID = "_id";
    //Tracking table
    public static String TRACK_NAME = "track_name";
    public static String CREATE_DATE = "create_date";
    public static String START_LOC = "start_loc";
    public static String END_LOC = "end_loc";

    //Schedule
    public static String TID = "tid";   //ID of the line
    public static String LAT = "lat";   //latitude
    public static String LNG = "lng";   //longitude

    private static String CREATE_TABLE_TRACK = "create table track(_id integer primary key autoincrement,track_name text,create_date text,start_loc text,end_loc text)";
    private static String CREATE_TABLE_TRACK_DETAIL = "create table track_detail(_id integer primary key autoincrement,tid integer not null,lat real,lng real)";

    private static int VERSION = 1;

    public DatabaseHelper(Context context) {
        super(context,DB_NAME,null,VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE_TRACK);
        db.execSQL(CREATE_TABLE_TRACK_DETAIL);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        if (newVersion > oldVersion) {
            db.execSQL("drop table if exists track");
            db.execSQL("drop table if exists track_detail");
            db.execSQL(CREATE_TABLE_TRACK);
            db.execSQL(CREATE_TABLE_TRACK_DETAIL);
        }
    }
}

You need to create a databaseAdapter class to add, delete, modify and query the database:

package com.example.map_track;


import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;

/**
 *Database Adapter 
 **/
public class DatabaseAdapter {
    private DatabaseHelper dbHelper;

    public DatabaseAdapter(Context context) {
        dbHelper = new DatabaseHelper(context);
    }

    //Add line trace
    public  int addTrack(Track track) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        //String sql = "insert to track(track_name,create_date,start_loc,end_loc) values(?,?,?,?)";
        //db.exceSQL(sql,new Object[]{track.getTrack_name(),track.getCreate_date(),track.getStart_loc(),track.getEnd_loc()});
        ContentValues values = new ContentValues();
        values.put(DatabaseHelper.TRACK_NAME, track.getTrack_name());
        values.put(DatabaseHelper.CREATE_DATE, track.getCreate_date());
        values.put(DatabaseHelper.START_LOC, track.getStart_loc());
        values.put(DatabaseHelper.END_LOC, track.getEnd_loc());
        long id = db.insertOrThrow(DatabaseHelper.TABLE_TRACK, null, values);
        db.close();
        return (int) id;
    }

    /**
     *Update destination address
     **/
    //At the beginning of walking, the starting point and the end point are in the same position. At the end, the end point changes. At this time, a function to update the end point position is required
    public void updateEndLoc(String endLoc, int id) {
        String sql = "update track set end_loc=? where _id=?";
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        db.execSQL(sql, new Object[] {endLoc, id});
        db.close();
    }

    //Add route tracking details
    public void addTrackDetail(int tid, double lat, double lng ) {  //tid is a foreign key
        SQLiteDatabase db= dbHelper.getWritableDatabase();
        String sql = "insert into track_detail(tid,lat,lng) values(?,?,?)";
        db.execSQL(sql, new Object[] {tid ,lat, lng});
        db.close();
    }

    //Query line tracking according to ID
    public ArrayList<TrackDetail> getTrackDetails(int id) {
        String sql = "select _id,lat,lng from track_detail where tid=? order by _id desc";
        ArrayList<TrackDetail> list = new ArrayList<TrackDetail>();
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor c= db.rawQuery(sql, new String[] { String.valueOf(id) });
        if (c != null) {
            TrackDetail detail = null;
            while (c.moveToNext()) {
                detail = new TrackDetail(c.getInt(0), c.getDouble(1),c.getDouble(2));
                list.add(detail);
            }
            c.close();
        }
        return list;
    }

    /**
     Query all lines
     **/
    public  ArrayList<Track> getTracks() {
        ArrayList<Track> tracks = new ArrayList<Track>();
        String sql = "select _id,track_name,create_date,start_loc,end_loc from track ";
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor c = db.rawQuery(sql, null);
        Track t = null;
        if (c != null) {
            while (c.moveToNext()) {
                t = new Track(c.getInt(0), c.getString(1), c.getString(2), c.getString(3), c.getString(4));
                tracks.add(t);
            }
            c.close();
        }
        db.close();
        return tracks;
    }

    //Delete line tracking by ID
    public void delTrack(int id) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        String sql1 = "delete from track where _id=?";
        String sql2 = "delete from track_detail where tid=?";
        try {
            db.beginTransaction();
            db.execSQL(sql2, new Object[] { id });
            db.execSQL(sql1, new Object[] { id });
            db.setTransactionSuccessful();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            db.endTransaction();
            if( db != null)
                db.close();
        }

    }
}


Another DateUtils class needs to be set for date conversion:

package com.example.map_track;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *Tool class for date conversion
 **/

public class DateUtils {

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public static String toDate(Date date) {
        return sdf.format(date);
    }
}

Next is the core class MainActivity:

package com.example.map_track;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
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.InfoWindow;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Polyline;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {

    public static final int PLAYBACK_OVER = 1;
    private MapView mapView;
    private BaiduMap baiduMap;
    private LocationClient mLocationClient = null;  //Define a listener object
    private MyLocationListener myLocationListener;
    private double currentLat, currentLng;  //Current latitude and longitude
    private String currentAddr;   //Current address
    private DatabaseAdapter dbAdapter;
    private GeoCoder geoCoder;
    private int currentTrackLineID; //Route ID currently tracked



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.activity_main);
        mapView = (MapView) findViewById(R.id.bmapView);
        initBaiduMap();     //Initialize the map to display my current location
        dbAdapter = new DatabaseAdapter(this);
    }
    /**
     * Initialize Baidu map
     */
    private void initBaiduMap() {
        baiduMap = mapView.getMap();
        baiduMap.setMyLocationEnabled(true);    //Turn on the positioning layer to allow positioning
        mLocationClient = new LocationClient(getApplicationContext());  //Declare LocationClient class
        myLocationListener = new MyLocationListener();
        mLocationClient.registerLocationListener(myLocationListener);   //Register listener function

        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy); //Set positioning mode
        option.setCoorType("bd09ll");   //The returned positioning result is Baidu longitude and latitude, and the default value is gcj02
        option.setScanSpan(5000);  //Set the interval between sending location requests to 5000ms
        option.setIsNeedAddress(true);  //The returned location result contains address information
        option.setNeedDeviceDirect(true);   //The returned positioning result includes the direction of the mobile phone head
        mLocationClient.setLocOption(option);
        mLocationClient.start();    //Start SDK location
        mLocationClient.requestLocation();  //Initiate location request

//Listener for converting geocoding
        geoCoder = GeoCoder.newInstance();
        geoCoder.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {
            @Override
            public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
                if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                    //No search results
                }
                else {
                    //Get geocoding results
                    //System.out.println(result.getAddress());
                    currentAddr = result.getAddress();
                    //End of line update
                    dbAdapter.updateEndLoc(currentAddr, currentTrackLineID);
                }
            }

            @Override
            public void onGetGeoCodeResult(GeoCodeResult arg0) {

            }
        });
    }
    boolean flag = true;

    /**
     * Location monitoring
     */
    class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location != null && flag) {
                flag = false;
                currentLat = location.getLatitude();    //Current latitude
                currentLng = location.getLongitude();   //Current longitude
                currentAddr = location.getAddrStr();     //Address of current location
                //System.out.println("currentAddr=" + currentAddr);
                //Construct my current location information
                MyLocationData.Builder builder = new MyLocationData.Builder();
                builder.latitude(location.getLatitude());   //Set latitude
                builder.longitude(location.getLongitude()); //Set longitude
                builder.accuracy(location.getRadius()); //Set precision (radius)
                builder.direction(location.getDirection()); //Set direction
                builder.speed(location.getSpeed()); //set speed
                MyLocationData locationData = builder.build();

                //Set my location information on the map
                baiduMap.setMyLocationData(locationData);
                //Configure my location
                LatLng latlng = new LatLng(currentLat , currentLng);
                baiduMap.setMyLocationConfiguration(new MyLocationConfiguration(MyLocationConfiguration.LocationMode.FOLLOWING,true,null));
                //Set my position as the center point of the map and enlarge the map 16 times (zoom level is 3-20)
                baiduMap.animateMapStatus(MapStatusUpdateFactory.newLatLngZoom(latlng, 20));

                //System.out.println("address:" + currentAddr + "--- latitude:" + currentLat + "--- longitude:" + currentLng+"\n");



            }
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    //Function menu item
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.mylocation :
                mylocation();   //My position
                break;
            case R.id.start_track :
                startTrack();   //Start tracking
                break;
            case R.id.end_track :
                endTrack();     //End tracking
                break;
            //       case R.id.track_back :
            //      trackBack();    // Tracking playback
            //          break;

            default:
                break;
        }
        return true;
    }



    /**
     * End tracking
     */
    private void endTrack() {
        isTracking = false;  //End thread
        Toast.makeText(MainActivity.this, "End of tracking...", Toast.LENGTH_SHORT).show();
        //Convert the geocode and convert the last longitude and latitude into an address (convert the longitude and latitude into the corresponding place name address, or convert the place name address into the corresponding longitude and latitude)
        geoCoder.reverseGeoCode(new ReverseGeoCodeOption().location(new LatLng(currentLat, currentLng)));
    }

    /**
     * My position
     */
    private void mylocation() {
        Toast.makeText(MainActivity.this, "Locating...", Toast.LENGTH_SHORT).show();
        flag = true;
        baiduMap.clear();   //Clear custom layers on the map
        baiduMap.setMyLocationEnabled(true);
        mLocationClient.requestLocation();  //Initiate location request
    }

    /**
     * Start tracking function
     */
    private void startTrack() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Line tracking");
        builder.setCancelable(true);
        final View view = getLayoutInflater().inflate(R.layout.add_track_line_dialog, null);
        builder.setView(view);
        builder.setPositiveButton("add to", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                EditText et_track_name = (EditText) view.findViewById(R.id.editText1_track_name);
                String trackName = et_track_name.getText().toString();
                System.out.println(trackName);
                createTrack(trackName);     //Create line trace
                Toast.makeText(MainActivity.this, "Tracking start...", Toast.LENGTH_SHORT).show();
            }
        });
        builder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.show();
    }

    //Create a line trace
    private void createTrack(String trackName) {
        Track track = new Track();
        track.setTrack_name(trackName);
        track.setCreate_date(DateUtils.toDate(new Date())); //The creation time is the current time
        track.setStart_loc(currentAddr);
        currentTrackLineID = dbAdapter.addTrack(track);   //Add a line and return the line ID
        dbAdapter.addTrackDetail(currentTrackLineID, currentLat, currentLng);   //Add details
//        baiduMap.clear();
        addOverlay();
        list.add(new LatLng(currentLat, currentLng));
        isTracking = true;   //Tag for thread emulation
        System.out.println(list);
        new Thread(new TrackThread()).start();
    }

    private boolean isTracking = false;

    //Simulated trace thread
    class TrackThread implements Runnable {
        @Override
        public void run() {
            while (isTracking) {
                getLocation();  //Get simulation location
                dbAdapter.addTrackDetail(currentTrackLineID, currentLat, currentLng);
                addOverlay();
                list.add(new LatLng(currentLat, currentLng));
                drawLine(); //Draw a line
                System.out.println("drawLine");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //Used to store the longitude and latitude of two adjacent points, and then draw lines
    private ArrayList<LatLng> list = new ArrayList<LatLng>();

    //Add layers to the map (each point of the circuit)
    private void addOverlay() {
        //--------Add a dimension overlay at the current location--------
        //Build Marker Icon
        baiduMap.setMyLocationEnabled(false);   //Turn off anchor layer
        BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.mipmap.ic_launcher_round);
        //Build a MakerOption to add a Marker to the map
        LatLng latlng = new LatLng(currentLat, currentLng);
        OverlayOptions option = new MarkerOptions().position(latlng).icon(bitmap);
        //Add a Marker on the map and display it
        baiduMap.addOverlay(option);
        //Take the currently added map location as the center point of the map
        baiduMap.animateMapStatus(MapStatusUpdateFactory.newLatLng(latlng));
    }

    //Draw a line between two points
    private void drawLine() {
        OverlayOptions lineOptions = new PolylineOptions().points(list).color(0xFFFF0000);
        baiduMap.addOverlay(lineOptions);
        list.remove(0); //This is to remove the previous one between two points, because after the first line drawing, only the second point needs to be added in each line drawing, but it adds both points by default and then draws a line, so the first point needs to be deleted
    }

    /**
     * Simulate the location. In real time, you should use the listener to obtain the geographic location information
     */
    private void getLocation() {
        currentLat = currentLat + Math.random() / 1000;
        currentLng = currentLng + Math.random() / 1000;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //Execute mmapview when the Activity executes onResume Onresume() to realize map life cycle management
        mapView.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //Execute mmapview when the Activity executes onResume Onresume() to realize map life cycle management
        mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //Execute mmapview when the Activity executes onPause Onpause() to realize map life cycle management
        mapView.onPause();
    }
}

Here, you need to set a menu item. When you click the menu item, you can pop up multiple options to realize the corresponding functions:
You need to create a menu folder under app/res and a main folder under menu XML file;

<menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/mylocation"
        android:orderInCategory="10"
        app:showAsAction="never"
        android:title="My position" />
    <item
        android:id="@+id/start_track"
        android:orderInCategory="100"
        android:title="Start tracking"
        app:showAsAction="never" />
    <item
        android:id="@+id/end_track"
        android:orderInCategory="200"
        android:title="End tracking"
        app:showAsAction="never" />
    <item
        android:id="@+id/track_back"
        android:orderInCategory="300"
        android:title="Tracking playback"
        app:showAsAction="never" />

</menu>

The general execution process of MainActivity:
First, initialize the SDK, and then initialize the map, that is, call the initBaiduMap method, set the positioning mode, and initiate the positioning request. In the requested MyLocationListener callback method, you can get the longitude and latitude information and display it on my location;
Next, click startTrack(), which is the method to start tracking, and add will be called here_ track_ line_ Dialog layout file, so you also need to create an add in the res/layout folder_ track_ line_ dialog. XML file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="16dp"
    android:orientation="vertical" >


    <EditText
        android:id="@+id/editText1_track_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Please enter tracking line name"
        android:ems="10"
        android:layout_marginBottom="5dp" >

        <requestFocus />
    </EditText>
    
    <EditText
        android:id="@+id/editText2_start_loc"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Starting position"

        android:cursorVisible="false"
        android:focusable="false"
        android:focusableInTouchMode="false"

        android:ems="10" />



</LinearLayout>

Next, the createTrack method will be called, which is a method to create a line trace; Then the addOverlay method will be called. This is to add a label covering at the current position. Each time a line segment is drawn on the line, the current longitude and latitude will be marked with a covering;
At this time, a new simulation location will be created by using the longitude and latitude of the thread () to simulate the current location, that is, a new location will be created by using the longitude and latitude of the thread ();
After determining the new position, call the line drawing method drawLine() to connect the two points with a line;

(other functions have not been implemented, such as tracking and playback. This has been written in the class. The rest is to add the corresponding callback function in MainActivity)
The line I use here is an analog line, which needs to be changed into the method of monitoring the GPS inside the mobile phone. Maybe you can take the mobile phone outside to actually test whether it is feasible

This is just the beginning of learning. What mistakes do you need the help of leaders to point out

Tags: Java Android app

Posted by realnsleo on Tue, 24 May 2022 20:03:34 +0300