Android learning column - Baidu map let Baidu map display (picture and text + code)

Keywords: Java Android Android Studio

Series articles

Tip: go to the Android learning column and watch more!
Click me directly – > Android learning column

preface

Create a new project named LBSTest.
Baidu map (5) let Baidu map display (picture and text + code)

Realization effect

activity_main.xml (modified)

  1. The content in the layout file is very simple, with only one TextView control for later display
    Longitude and latitude information of the front position.
  2. A new MapView control is placed in the layout file and fills the entire screen
    Curtain. This MapView is a custom control provided by Baidu, so you need to use it
    Add the full package name. In addition, the TextView previously used to display positioning information is now temporarily displayed
    We specify its visibility attribute as gone and let it be displayed on the interface
    Hide.
<?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" >
    <TextView
        android:id="@+id/position_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="gone" />
    <com.baidu.mapapi.map.MapView
        android:id="@+id/bmapView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clickable="true" />
</LinearLayout>

AndroidManifest.xml

  1. The AndroidManifest.xml file has changed a lot. Let's read it carefully. As you can see, many line permission statements have been added here. Each permission is used internally in Baidu LBS SDK. Then a < metadata > tag is added inside the tag. The android:name part of the tag is fixed and must be com.baidu.lbsapi.API_KEY, android:value should be filled in our previous articles
    Android learning column - Android obtains SHA1 fingerprint, applies for Baidu map API Key, and uses Baidu LBS positioning function (Graphic nanny level)
    API Key requested.
  2. If your "android:name =" com.baidu.location.f "is red, there is a problem with the previous jar configuration
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.lbstest">
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/Theme.AppCompat">
        <meta-data
            android:name="com.baidu.lbsapi.API_KEY"
            android:value="Fill in the information you applied for earlier api key" />
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <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>

MainActivity.java (modified)

First, in the initLocation() method, we call the setIsNeedAddress() method of LocationClientOption and pass in true, which means that we need to obtain the detailed address information of the current location. Next, in the onReceiveLocation() method of MyLocationListener, you can get various rich address information. Call the getCountry() method to get the current country, call the getProvince() method to get the current province, and so on. In addition, it should be noted that the network must be used to obtain the address information, so even if we specify the location mode as Device_Sensors will also automatically turn on the network positioning function.

package com.example.lbstest;

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

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.widget.TextView;
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.MapView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    public LocationClient mLocationClient;
    private TextView positionText;
    //Start of modification
    private MapView mapView;
    //End of modification
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //Start of modification
        //First, you need to call the of SDKInitializer
        //initialize() method, which receives a
        //A Context parameter. Here we call the getApplicationContext() method to get
        //Take a global Context parameter and pass it in. Note that the initialization operation must be
        //Call before setContentView() method, otherwise you will make a mistake. Next, let's adjust
        //The instance of MapView is obtained with the findViewById() method
        super.onCreate(savedInstanceState);
        mLocationClient = new LocationClient(getApplicationContext());
        mLocationClient.registerLocationListener(new MyLocationListener());
        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.activity_main);
        mapView = (MapView) findViewById(R.id.bmapView);
        //End of modification
        positionText = (TextView) findViewById(R.id.position_text_view);
        List<String> permissionList = new ArrayList<>();
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.
                permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.
                permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            permissionList.add(Manifest.permission.READ_PHONE_STATE);
        }
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.
                permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
        if (!permissionList.isEmpty()) {
            String[] permissions = permissionList.toArray(new String[permissionList.
                    size()]);
            ActivityCompat.requestPermissions(MainActivity.this, permissions, 1);
        } else {
            requestLocation();
        }
    }

    private void requestLocation() {
        initLocation();
        mLocationClient.start();
    }

    private void initLocation() {
        LocationClientOption option = new LocationClientOption();
        option.setScanSpan(5000);
        option.setIsNeedAddress(true);
        mLocationClient.setLocOption(option);
    }

    //To override onResume(), onPause(), and onDestroy()
    //MapView is managed here to ensure that resources can be released in time.
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

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

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mLocationClient.stop();
        mapView.onDestroy();
    }
    //The newly modified content is updated in real time, and the location ends


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                           int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0) {
                    for (int result : grantResults) {
                        if (result != PackageManager.PERMISSION_GRANTED) {
                            Toast.makeText(this, "You must agree to all permissions to use this program",
                                    Toast.LENGTH_SHORT).show();
                            finish();
                            return;
                        }
                    }
                    requestLocation();
                } else {
                    Toast.makeText(this, "An unknown error occurred", Toast.LENGTH_SHORT).show();
                    finish();
                }
                break;
            default:
        }
    }

    public class MyLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    StringBuilder currentPosition = new StringBuilder();
                    currentPosition.append("Latitude:").append(location.getLatitude()).
                            append("\n");
                    currentPosition.append("Longitude:").append(location.getLongitude()).
                            append("\n");
                    currentPosition.append("country:").append(location.getCountry()).
                            append("\n");
                    currentPosition.append("Province:").append(location.getProvince()).
                            append("\n");
                    currentPosition.append("City:").append(location.getCity()).
                            append("\n");
                    currentPosition.append("Zone:").append(location.getDistrict()).
                            append("\n");
                    currentPosition.append("street:").append(location.getStreet()).
                            append("\n");
                    currentPosition.append("Positioning mode:");
                    if (location.getLocType() == BDLocation.TypeGpsLocation) {
                        currentPosition.append("GPS");
                    } else if (location.getLocType() ==
                            BDLocation.TypeNetWorkLocation) {
                        currentPosition.append("network");
                    }
                    positionText.setText(currentPosition);
                }
            });
        }

        //     @Override
        public void onConnectHotSpotMessage(String s, int i) {
        }
    }
}

Appendix. References

The first line of code 11.4 uses Baidu map

Download resources

Android learner Baidu map (5) let Baidu map display

summary

If you like, give me a 👍, Pay attention! Continue to share with you the problems encountered in the process of typing code!

Posted by Paul15679 on Tue, 23 Nov 2021 02:16:11 -0800