Baidu map positioning APP

1, Function introduction

1. Ordinary map and satellite map can be realized.
2. You can display the positioning point of the current location in your own map.
3. Click, double-click, long press, zoom, rotate, change perspective and other operations of the map can be realized through interface or gesture control.

2, Steps and key codes

1. Android studio configuration
(1) Enter the baidu map open platform, log in and find the console → my application → create an application.
(2) Click to enter and fill in relevant information.
Enter the app name, select the app type, and enabled services.

Get release SHA1
Provide commands based on official documents


Find the directory where the local keystore is located, replace the directory in the command, and enter the command in the Terminal of as to obtain the distribution board SHA1.


Create a new project. Open AndroidManifest.xml and copy the package name as PackageName.


The application was created successfully and AK code was obtained.


(3) Click development documentation, select Android map SDK, click development guide, select Android Studio configuration, and click download installation package.


(4) Select basic location, basic map and JAR, and then download the development package.


(5) After downloading, unzip the folder and enter libs.


Copy these six files, enter Android Studio, switch to Project mode, and paste them into app/libs directory.


Configure the sourceSets tag in the android block in the build.gradle file in the app directory, copy the following code into the android closure, and then Sync to save the modified configuration file.

sourceSets {
        main {
            jniLibs.srcDir 'libs'
        }
    }


2. Display map
(1) Configure the AndroidManifest.xml file
Add the following code to configure the development key (AK)

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

Add the following permission statement externally

<!-- Access the network and request map related business data, including map data, route planning, POI Search, etc -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- Obtain the network state, and perform data request network conversion according to the network state switching -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    
<!-- Read external storage. If developers use so Dynamic loading function and so If the file is placed in an 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" />
<!-- 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" /> 

(2) Add a map container to a layout file

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

(3) Map initialization
Create a custom Application and complete SDK initialization in its onCreate method. The code is as follows

public class MyLBS extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        //Before using SDK components, initialize the context information and pass in ApplicationContext   
        SDKInitializer.initialize(this);
        //Since 4.3.0, all interfaces of Baidu map SDK support Baidu coordinates and National Survey Bureau coordinates. Use this method to set the coordinate type you use
        //It includes BD09LL and GCJ02 coordinates. The default is BD09LL coordinates.
        SDKInitializer.setCoordType(CoordType.BD09LL);
    }
}

Declare the Application in the AndroidManifest.xml file

<application
        android:name=".MyLBS"

(4) Create a map Activity and manage the MapView lifecycle

public class MainActivity extends Activity {  
    private MapView mapView;  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);    
        setContentView(R.layout.activity_main);  
        //Get map control reference  
        mapView=findViewById(R.id.bmapView);  
    }  
    @Override  
    protected void onResume() {  
       super.onResume();  
       //When the activity executes onResume, execute mMapView. onResume() to realize map life cycle management  
       mapView.onResume();  
    }  
    @Override  
    protected void onPause() {  
      super.onPause();  
      //When the activity executes onPause, execute mMapView. onPause() to realize map life cycle management  
      mapView.onPause();  
    } 
    @Override  
    protected void onDestroy() {  
      super.onDestroy();  
      //When the activity executes onDestroy, execute mMapView.onDestroy() to realize map life cycle management  
      mapView.onDestroy();  
    }  

3. Switch map type
Set up satellite map

mBaiduMap = mMapView.getMap();
//Satellite map   
mBaiduMap.setMapType(BaiduMap.MAP_TYPE_SATELLITE);   

4. Display positioning
(1) Configure the AndroidManifest.xml file
Add the following permission statement

<!-- This permission is used for network location -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!-- This permission is used to access GPS location -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Declare the located service component in the Application tag

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

(2) Turn on the positioning layer of the map

mBaiduMap.setMyLocationEnabled(true);

(3) Construct map data
Obtain the location data by inheriting the abstract class BDAbstractListener and rewriting its onreceivelocation method, and pass it to MapView.

private boolean isFirstLocate = true;
// Is this the first positioning
public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            //After mapView is destroyed, it is not in the location where new reception is processed
            if (location == null || mapView == null){
                return;
            }
            // If it is the first positioning
            LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
            if (isFirstLocate) {
                isFirstLocate = false;
                //Set status for map
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newLatLng(ll));
            }
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // Set the direction information obtained by the developer here, clockwise 0-360
                    .direction(location.getDirection()).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mBaiduMap.setMyLocationData(locData);
            
        }
    }

(4) Create initLocation function and initiate location through LocationClient

public void initLocation() {
        
        //Positioning initialization
        mLocationClient = new LocationClient(this);
        //Set LocationClient related parameters through LocationClientOption
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // Turn on gps
        option.setCoorType("bd09ll"); // Set coordinate type
        option.setScanSpan(1000);
        // Optional, set the address information
        option.setIsNeedAddress(true);
        //Optional, set whether address description is required
        option.setIsNeedLocationDescribe(true);
        //Setting locationClientOption
        mLocationClient.setLocOption(option);

        //Register LocationListener listener
        MyLocationListener myLocationListener = new MyLocationListener();
        mLocationClient.registerLocationListener(myLocationListener);
        //Turn on map positioning layer
        mLocationClient.start();
    }

(5) Correctly manage the life cycle of each part

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

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

@Override
protected void onDestroy() {
    mLocationClient.stop();
    mBaiduMap.setMyLocationEnabled(false);
    mapView.onDestroy();
    mapView = null;
    super.onDestroy();
}

5. Display latitude and longitude and address

private TextView mtextView;

mtextView = findViewById(R.id.text_tishi);

Write in MyLocationListener

StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("\n Longitude:" + location.getLatitude());
            stringBuilder.append("\n Latitude:"+ location.getLongitude());
            stringBuilder.append("\n Address:" + location.getAddrStr());

3, Operation effect display

1. General map

2. Satellite map

3. Positioning and longitude and latitude address display

4, Source code warehouse address

https://gitee.com/huang-jingwen0328/LBS

Tags: Android Studio

Posted on Sat, 04 Dec 2021 16:11:44 -0500 by cainscripter