Android learning column - Baidu map moves to my location (picture and text + code)

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 (6) moves to my location (picture and text + code)
The map is successfully displayed, but maybe it's not what you want. Because this is a default
The map shows the location of central Beijing, and you may want to see more detailed land
Figure information, such as the surrounding environment of your location. Obviously, by scaling and moving the square
It's foolish to find your place slowly. So let's learn this section
Learn how to quickly move to your location in the map.

Introduce api

The API of Baidu LBS SDK provides a BaiduMap class, which is the general controller of the map. You can get the instance of BaiduMap by calling the getMap() method of MapView.

BaiduMap baiduMap = mapView.getMap();

With BaiduMap, we can perform various operations on the map, such as setting
Zoom level of the map and move the map to a latitude and longitude. Baidu map limits the value range of zoom level between 3 and 19, in which the value of decimal point can also be taken. The larger the value, the finer the information displayed on the map. For example, we want to shrink
Set the zoom level to 12.5:
The zoomTo() method of MapStatusUpdateFactory receives a float type parameter
The number is used to set the zoom level. Here we pass in 12.5f. zoomTo() method returns
A MapStatusUpdate object is returned. We pass this object into Baidu map
The zooming function can be completed in the animateMapStatus() method.

MapStatusUpdate update = MapStatusUpdateFactory.zoomTo(12.5f);
baiduMap.animateMapStatus(update);

The latlng class is needed to move the map to a certain latitude and longitude. In fact, latlng stores longitude and latitude values. Its construction method receives two parameters. The first parameter is latitude value and the second parameter is longitude value. After calling the newLatLng() method of MapStatusUpdateFactory, the LatLng object is passed in, and the newLatLng() method returns a MapStatusUpdate object. After we have passed the object into the animateMapStatus() method of BaiduMap, we can move the map to the specified latitude and longitude, so that we can move the map to 39.915 degrees north latitude. Code for 116.404 degrees east longitude:

LatLng ll = new LatLng(39.915, 116.404);
MapStatusUpdate update = MapStatusUpdateFactory.newLatLng(ll);
baiduMap.animateMapStatus(update);

Realization effect

activity_main.xml

  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)

Added a navigateTo() method. Extract and encapsulate as like as two peas of the BDLocation object, and then encapsulate it into the LatLng object. Then, call the newLatLng() method of MapStatusUpdateFactory and import the LatLng object, then pass the returned MapStatusUpdate object as parameter to the animateMapStatus() method of BaiduMap, which is exactly the same as the one introduced above. In order to enrich the map information, we set the zoom level
It's 16.
In the above code, we use an isFirstLocate variable to prevent multiple calls to the animateMapStatus() method, because moving the map to our current location only requires
Just call it once when the program is located for the first time.
After writing the navigateTo() method, the rest is simple. When locating the current location of the device, we directly pass the BDLocation object to the navigateTo() method in the onReceiveLocation() method, so that the map can be moved to the location of the device.

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.BaiduMap;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.model.LatLng;

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

public class MainActivity extends AppCompatActivity {
    public LocationClient mLocationClient;
    private TextView positionText;
    private MapView mapView;
    //Start of modification
    private BaiduMap baiduMap;
    private boolean isFirstLocate = true;
    //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);
        baiduMap = mapView.getMap();
        //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 navigateTo(BDLocation location) {
        if (isFirstLocate) {
            LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
            MapStatusUpdate update = MapStatusUpdateFactory.newLatLng(ll);
            baiduMap.animateMapStatus(update);
            update = MapStatusUpdateFactory.zoomTo(16f);
            baiduMap.animateMapStatus(update);
            isFirstLocate = false;
        }
    }
    public class MyLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location.getLocType() == BDLocation.TypeGpsLocation
                    || location.getLocType() == BDLocation.TypeNetWorkLocation) {
                navigateTo(location);
            }
        }
    }

    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:
        }
    }
}

Appendix. References

First line code 11.5 moved to my position

Download resources

Android learner Baidu map (6) moves to my location

summary

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

Keywords: Java Android Android Studio

Added by kbdrand on Wed, 24 Nov 2021 03:52:24 +0200