Using Baidu map api in Android

Keywords: Android network xml Gradle

Preparatory work: before use, you need to apply for API Key on Baidu developer platform, which is not covered here. You can query the article by yourself.

1, Modify the AndroidManifest.xml file to add permissions and API keys. The following are permissions needed (the annotation part is because the project has been added before, and the reader still needs to register)

<!--&lt;!&ndash; Read permission &ndash;&gt;-->
    <!--<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />-->
    <!--<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />-->

    <!--Baidu map needs permission-->
    <!--<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>-->
    <!--&lt;!&ndash;//Get device network status. When disabled, the network status cannot be obtained & ndash; & gt; -- >
    <!--<uses-permission android:name="android.permission.INTERNET"/>-->
    <!--&lt;!&ndash;//When network permission is disabled, retrieval and other related businesses cannot be performed
    <!--<uses-permission android:name="android.permission.READ_PHONE_STATE" />-->
    <!--&lt;!&ndash;//Read device hardware information, statistics & ndash; & gt; -- >
    <!--<uses-permission android:name="com.android.launcher.permission.READ_SETTINGS" />-->
    <!--&lt;!&ndash;//Read system information, including system version and other information, for Statistics & ndash; & gt; -- >
    <!--<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />-->
    <!--&lt;!&ndash;//Get the network status of the device and the network agent needed for authentication & ndash; & gt; -- >
    <!--<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>-->
    <!--//The sd card is allowed to write permissions, and map data needs to be written. After disabling, the map cannot be displayed -- >
    <uses-permission android:name="android.permission.WRITE_SETTINGS" />
    <!--//Get statistics -- >
    <uses-permission android:name="android.permission.GET_TASKS" />
    <!--//This permission is required for authentication to obtain the process list -- >
    <uses-permission android:name="android.permission.CAMERA" />
    <!--//Use walking AR navigation to configure Camera permissions -- >
<application
    ...>
<meta-data
            android:name="com.baidu.lbsapi.API_KEY"
            android:value="Fill in the application here API Key"
            />
<application>

2, Add the following code to build.gradle

android{
sourceSets{
    main{
        jniLibs.srcDir 'libs'
        //Note that the path of so is the libs path, associated with all map SDK so files
    }
}
dependencies {
    implementation files('libs/BaiduLBS_Android.jar')
    compile files('libs/BaiduLBS_Android.jar')
}

3, Import and download the good jar package in libs under the project directory (it needs to be downloaded from Baidu Developer Platform): right click the jar package and click Add as Library

4, Place a MapView map in XML and set various parameters in Activity

<com.baidu.mapapi.map.MapView
        android:id="@+id/bmapView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:clickable="true" />
public class MapActivity extends Activity {
    BaiduMap mBaiduMap;//Defining map instances
    MapView mMapView;
    public LocationClient mLocationClient = null;//Define LocationClient
    private MyLocationListener myListener = new MyLocationListener();//Inherit the class of BDAbstractLocationListener
    boolean ifFrist = true;//Determine if it's the first time in
    class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            //BDLocation is the location result information class. All the results related to location can be obtained through its various get methods
            //The following is a partial list of results related to latitude and longitude (commonly used)
            //For more result information, refer to the description in BDLocation class in class reference

            double latitude = location.getLatitude();    //Get latitude information
            double longitude = location.getLongitude();    //Get longitude information
            float radius = location.getRadius();    //Get positioning accuracy, the default value is 0.0f

            String coorType = location.getCoorType();
            //Obtain the latitude and longitude coordinate type, which is subject to the coordinate type set in LocationClientOption

            int errorCode = location.getLocType();
            Log.i("---------", location.getCityCode() + "---" + latitude + "--" + longitude + "----" + coorType + "--" + location.getCountry() + "--" + location.getCity() + "--" + location.getAddrStr());
            //Get the location type and location error return code. For details, please refer to the description in BDLocation class in the class reference

            // Construct location data
	        MyLocationData locData = new MyLocationData.Builder()
	                .accuracy(location.getRadius())
	                // Set the direction information obtained by the developer here, clockwise 0-360
	                .direction(100).latitude(location.getLatitude())
	                .longitude(location.getLongitude()).build();

	        // Set location data
	        mBaiduMap.setMyLocationData(locData);

            if (ifFrist) {
                MapStatusUpdate update = MapStatusUpdateFactory.zoomBy(5f);
                // enlarge
                mBaiduMap.animateMapStatus(update);
                // Show personal location, locate data builder
                MyLocationData.Builder builder = new MyLocationData.Builder();
                builder.latitude(location.getLatitude());
                builder.longitude(location.getLongitude());
                MyLocationData data = builder.build();
                mBaiduMap.setMyLocationData(data);
                ifFrist = false;
            }
        }
    }
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SDKInitializer.initialize(getApplicationContext());

        setContentView( R.layout.maplayout);
        mMapView = (MapView) findViewById(R.id.bmapView);
        mBaiduMap = mMapView.getMap();//Get map instance object
        // Turn on positioning layer
        mBaiduMap.setMyLocationEnabled(true);
        //Set the positioning icon, the second parameter to set whether there is an arrow, and the third to set the icon style
        //mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration(MyLocationConfiguration.LocationMode.FOLLOWING, false,null));
        mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration(MyLocationConfiguration.LocationMode.FOLLOWING, false, null));


        //Declare LocationClient class
        mLocationClient = new LocationClient(getApplicationContext());
        //Register listening function
        mLocationClient.registerLocationListener(myListener);

        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        //Optional, set positioning mode, default high precision
        //Locationmode. High "accuracy:;
        //Locationmode. Battery "saving: low power consumption;
        //Locationmode. Device? Sensors: use only devices;

        option.setCoorType("bd09ll");
        //Optional, set to return to latitude and longitude coordinate type, default gcj02
        //gcj02: coordinates of National Survey Bureau;
        //bd09ll: Baidu latitude and longitude coordinates;
        //bd09: Baidu Mercator coordinate;
        //For positioning in overseas areas, it is not necessary to set coordinate type and return wgs84 type coordinates in a unified way

        option.setScanSpan(10000);
        //Optional, set the interval for initiating location request, int type, unit: ms
        //If it is set to 0, it means single positioning, that is, positioning only once, and the default is 0
        //If the setting is not 0, it needs to be set for more than 1000ms to be effective

        option.setOpenGps(true);
        //Optional, set whether to use gps, default false
        //The parameter must be set to true if two positioning modes are used: high precision and device only

        option.setLocationNotify(true);
        //Optional, set whether to output GPS result according to 1S/1 frequency when GPS is valid, default is false

        option.setIgnoreKillProcess(false);
        //Optionally, locate a service inside the SDK and put it into a separate process.
        //Set whether to kill this process during stop. It is not killed by default (recommended), that is, setIgnoreKillProcess(true)

        option.SetIgnoreCacheException(false);
        //Optional, set whether to collect Crash information. The default collection parameter is false

        option.setWifiCacheTimeOut(5 * 60 * 1000);
        //Optional, new capability of version 7.2
        //If the interface is set, when starting positioning for the first time, it will first determine whether the current WiFi is beyond the validity period. If it is beyond the validity period, it will rescan the WiFi first, and then locate

        option.setEnableSimulateGps(false);
        //Optional. Set whether to filter GPS simulation results. The default value is false
        option.setIsNeedAddress(true);

        //Incoming location client set location client options
        mLocationClient.setLocOption(option);
        //Call LocationClient's start() method to initiate a location request
        mLocationClient.start();

    }
    protected void onStop() {
        super.onStop();
    }
    protected void onDestroy() {
        super.onDestroy();
        //When the activity executes onDestroy, execute mMapView.onDestroy() to implement Map lifecycle management
        mMapView.onDestroy();
        mLocationClient.stop();
        // Turn off anchor layer
        mBaiduMap.setMyLocationEnabled(false);

    }
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }
    protected void onResume() {
        super.onResume();
        //When the activity executes onResume, execute mMapView. onResume() to implement Map lifecycle management
        mMapView.onResume();
        //Call LocationClient's start() method to initiate a location request
        mLocationClient.start();
    }
}

Readers who have applied for api key can modify the package name on Baidu developer website (it needs to be consistent with the applicationId of defaultConfig in the file build.gradle), and then go through the above process

Posted by bcarlson on Sat, 04 Jan 2020 13:46:00 -0800