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 (7) let "I" display on the map (picture and text + code)
There should be a small cursor on the mobile phone map to display the current position of the device. If the device is moving, the cursor will also move with it. So let's continue to extend the existing code so that "I" can be displayed on the map.
Introduce api
Baidu LBS SDK provides a MyLocationData.Builder class, which is used to encapsulate the current location of the device. We only need to pass the longitude and latitude information into the corresponding methods of this class:
MyLocationData.Builder locationBuilder = new MyLocationData.Builder(); locationBuilder.latitude(39.915); locationBuilder.longitude(116.404);
The MyLocationData.Builder class also provides a build() method when we put
After the information to be encapsulated is set, you only need to call its build() method to generate
Create an instance of MyLocationData, and then transfer this instance to the
In the setMyLocationData() method, the current position of the device can be displayed on the ground
It's on the picture
MyLocationData locationData = locationBuilder.build(); baiduMap.setMyLocationData(locationData);
Realization effect
activity_main.xml
- 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. - 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
- 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. - 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
The first line of code 11.6 allows "I" to be displayed on the map
Download resources
Android learner Baidu map (7) example of "I" displayed on the map
summary
If you like, give me a 👍, Pay attention! Continue to share with you the problems encountered in the process of typing code!