Android studio Baidu map development (2) map Positioning

Source: Internet
Author: User

Android studio Baidu map development (2) map Positioning

Android studio Baidu map development (2) map Positioning

Email: chentravelling@163.com

Development Environment: win7 64-bit,Android Studio, Please note that it is Android Studio.

For Map Display and project configuration, see: Android studio Baidu map development (1) configure the project and display Map

I. Do something for Baidu

At first, I wrote it from start to end, but I was unable to locate it. I did not find the reason. Later, I used the Demo on the Baidu official website to get it out, it is basically from Baidu Demo. If you are fond of sputation, please show mercy on the keyboard and then let's see it.

Baidu has always liked Baidu, even though Baidu cannot be compared with Google. However, in the Chinese Technological atmosphere, I think Baidu is good enough, so I also posted some advantages of Baidu map positioning SDK.

Finally, I would like to ask those friends who call Baidu and cannot do without Baidu: What have you done for Chinese technology, IT, and society?

2. Locate the SDK Application

Let's get down to the truth. First paste the code of the entire project, and then explain it in the third part.

(1) BaiDuMapActivity. java
Package intvehapp. intvehapp; 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. mapStatus; import com. baidu. mapapi. map. mapStatusUpdateFactory; import com. baidu. mapapi. map. mapView; import com. baidu. mapapi. map. myLocationData; import com. baidu. mapapi. model. latLng; import android. app. activity; import android. OS. bundle; public class BaiDuMapActivity extends Activity {/*** locate SDK core class */private LocationClient locationClient;/*** locate listener */public MyLocationListenner myListener = new MyLocationListenner (); /*** Baidu map control */private MapView mapView;/*** Baidu map object */private BaiduMap baiduMap; boolean isFirstLoc = true; // determine whether to locate @ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); SDKInitializer. initialize (getApplicationContext (); setContentView (R. layout. activity_bai_du_map);/*** map initialization * // obtain the Baidu map control mapView = (MapView) findViewById (R. id. bmapView); // obtain the Baidu map object baiduMap = mapView. getMap (); // enable the position layer baiduMap. setMyLocationEnabled (true);/*** locate initialization * // declare and locate the SDK core class locationClient = new LocationClient (this); // register the listener locationClient. registerLocationListener (myListener); // locate the configuration information LocationClientOption option = new LocationClientOption (); option. setOpenGps (true); // enable gps option. setCoorType ("bd09ll"); // sets the coordinate type option. setScanSpan (1000); // request interval locationClient. setLocOption (option); // enable locationClient. start ();}/*** locate the SDK listener function */public class MyLocationListenner implements BDLocationListener {@ Override public void onReceiveLocation (BDLocation location) {// After map view is destroyed, if (location = null | mapView = null) {return;} MyLocationData locData = new MyLocationData is not processed in the newly received location. builder (). accuracy (location. getRadius () // set the direction information obtained by the developer, Which is 0-360 clockwise. direction (100 ). latitude (location. getLatitude ()). longpolling (location. getlongpolling ()). build (); baiduMap. setMyLocationData (locData); if (isFirstLoc) {isFirstLoc = false; LatLng ll = new LatLng (location. getLatitude (), location. getlongpolling (); MapStatus. builder builder = new MapStatus. builder (); builder.tar get (ll ). zoom (18.0f); baiduMap. animateMapStatus (MapStatusUpdateFactory. newMapStatus (builder. build () ;}} public void onReceivePoi (BDLocation poiLocation) {}}@ Override protected void onPause () {mapView. onPause (); super. onPause () ;}@ Override protected void onResume () {mapView. onResume (); super. onResume () ;}@ Override protected void onDestroy () {// destroy the locationClient when exiting. stop (); // close the position layer baiduMap. setMyLocationEnabled (false); mapView. onDestroy (); mapView = null; super. onDestroy ();}}

(2) activity_bai_du_map.xml: Add Baidu map control

 

 

 
     
  
 

(3) AndroidManifest. xml: add permissions, API_KEY, and location services required by Baidu map SDK

 

 

<!--{cke_protected}{C}%3C!%2D%2D%3Fxml%20version%3D%221.0%22%20encoding%3D%22utf-8%22%3F%2D%2D%3E--><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="intvehapp.intvehapp">    <!--{cke_protected}{C}%3C!%2D%2D%20%E7%99%BE%E5%BA%A6%E5%9C%B0%E5%9B%BEAPI%E6%89%80%E9%9C%80%E6%9D%83%E9%99%90%20%2D%2D%3E-->    <uses-permission android:name="android.permission.GET_ACCOUNTS">    <uses-permission android:name="android.permission.USE_CREDENTIALS">    <uses-permission android:name="android.permission.MANAGE_ACCOUNTS">    <uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS">    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE">    <uses-permission android:name="android.permission.INTERNET">    <uses-permission android:name="com.android.launcher.permission.READ_SETTINGS">    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE">    <uses-permission android:name="android.permission.ACCESS_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.BROADCAST_STICKY">    <uses-permission android:name="android.permission.WRITE_SETTINGS">    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION">    <!--{cke_protected}{C}%3C!%2D%2D%20%E8%AE%BF%E9%97%AE%E7%B2%BE%E7%A1%AE%E4%BD%8D%E7%BD%AE%E7%9A%84%E6%9D%83%E9%99%90%20%2D%2D%3E-->    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION">    <application android:allowbackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsrtl="true" android:theme="@style/AppTheme">        <activity android:name=".BaiDuMapActivity">            <intent-filter>                <action android:name="android.intent.action.MAIN">                <category android:name="android.intent.category.LAUNCHER">            </category></action></intent-filter>        </activity>        <!--{cke_protected}{C}%3C!%2D%2D%E7%99%BE%E5%BA%A6API_KEY%2D%2D%3E-->        <meta-data android:name="com.baidu.lbsapi.API_KEY" android:value="iXDGdZtFiPifnNm6dUEFwDRXYQVeZ37V">        <!--{cke_protected}{C}%3C!%2D%2D%E7%99%BE%E5%BA%A6%E5%AE%9A%E4%BD%8D%E6%9C%8D%E5%8A%A1%2D%2D%3E-->        <service android:name="com.baidu.location.f" android:enabled="true" android:process=":remote">        </service>    </meta-data></application></uses-permission></uses-permission></uses-permission></uses-permission></uses-permission></uses-permission></uses-permission></uses-permission></uses-permission></uses-permission></uses-permission></uses-permission></uses-permission></uses-permission></uses-permission></manifest>

OK. You can locate these three parts successfully. The effect is as follows:

3. Find SDK instructions

[From Baidu official website http://lbsyun.baidu.com/index.php? Title = android-locsdk/guide/getloc]

[Class reference: http://wiki.lbsyun.baidu.com/cms/androidloc/doc/v6_0_3/doc/index.html]

Step 1: Initialize the LocationClient class

Note that the LocationClient class must be declared in the main thread. Parameters of the Context type are required.

GetApplicationConext is recommended to obtain the Context that is valid throughout the process when the context is required.


Public LocationClient mLocationClient = null; public BDLocationListener myListener = new MyLocationListener (); public void onCreate () {mLocationClient = new LocationClient (getApplicationContext (); // declare the LocationClient class mLocationClient. registerLocationListener (myListener); // registers the listener function}

LocationClientClass is the core class for locating the SDK. For more information about the methods, see class reference.

Step 2: Configure and locate the SDK Parameters

 

Positioning parameters include: positioning mode (high-precision positioning mode, low-power positioning mode, and device-only positioning mode), return coordinate type, whether to enable GPS, whether to return address information, location semantic information, and POI information.

LocationClientOptionClass, which is used to set the SDK Positioning method, e.g .:

Private void initLocation () {LocationClientOption option = new LocationClientOption (); option. setLocationMode (LocationMode. hight_Accuracy); // optional. The default value is high precision. The positioning mode is set to high precision and low power consumption. Only the device option is used. setCoorType ("bd09ll"); // optional. The default value is gcj02. The returned Positioning Result coordinate system is set to int span = 1000; option. setScanSpan (span); // optional. The default value is 0, that is, only one request is located. Setting the interval between initiating a location request must be greater than or equal to MS is the effective option. setIsNeedAddress (true); // optional. Specifies whether address information is required. option is not required by default. setOpenGps (true); // optional. The default value is false. Set whether to use gps option. setLocationNotify (true); // optional. The default value is false. Set whether to output the gps result at 1 S1 frequency when GPS is valid. option. setIsNeedLocationDescribe (true); // optional. The default value is false. You can set whether location semantic results are required in BDLocation. getLocationDescribe. The result is similar to "near Tiananmen Square, Beijing" option. setIsNeedLocationPoiList (true); // optional. The default value is false. You can set whether POI results are required in BDLocation. get option in getPoiList. setIgnoreKillProcess (false); // optional. The default value is true. This parameter indicates that the SDK contains a SERVICE and is released to an independent process. This parameter indicates whether to kill the process during the stop operation. By default, no option is killed. setIgnoreCacheException (false); // optional. The default value is false. Set whether to collect CRASH information. The default value is "option. setEnableSimulateGps (false); // optional. The default value is false. It specifies whether to filter the gps simulation results. mLocationClient is required by default. setLocOption (option );}

High-precision positioning mode: In this mode, Network Positioning and GPS positioning are used at the same time to return the highest-precision positioning results;

Low-Power positioning mode: In this mode, GPS is not used, but Network Positioning (Wi-Fi and base station positioning) is used );

Only use the device positioning mode: In this positioning mode, you do not need to connect to the network, but only use GPS for positioning. In this mode, location in the indoor environment is not supported.

Step 3: implement the BDLocationListener Interface

The BDLocationListener interface has one method to implement: 1. Receive the location result returned asynchronously. The parameter is a BDLocation parameter.

Public class MyLocationListener implements BDLocationListener {@ Override public void onid elocation (BDLocation location) {// Receive Location StringBuffer sb = new StringBuffer (256); sb. append ("time:"); sb. append (location. getTime (); sb. append ("\ nerror code:"); sb. append (location. getLocType (); sb. append ("\ nlatitude:"); sb. append (location. getLatitude (); sb. append ("\ nlontitude:"); sb. append (location. getlongpolling (); sb. append ("\ nradius:"); sb. append (location. getRadius (); if (location. getLocType () = BDLocation. typeGpsLocation) {// GPS location result sb. append ("\ nspeed:"); sb. append (location. getSpeed (); // unit: kilometers per hour sb. append ("\ nsatellite:"); sb. append (location. getSatelliteNumber (); sb. append ("\ nheight:"); sb. append (location. getAltitude (); // unit: meter sb. append ("\ ndirection:"); sb. append (location. getDirection (); // unit sb. append ("\ naddr:"); sb. append (location. getAddrStr (); sb. append ("\ ndescribe:"); sb. append ("gps Positioning successful");} else if (location. getLocType () = BDLocation. typeNetWorkLocation) {// network location result sb. append ("\ naddr:"); sb. append (location. getAddrStr (); // carrier information sb. append ("\ noperationers:"); sb. append (location. getOperators (); sb. append ("\ ndescribe:"); sb. append ("Network Positioning successful");} else if (location. getLocType () = BDLocation. typeOffLineLocation) {// offline location result sb. append ("\ ndescribe:"); sb. append ("offline location successful, offline location result is also valid");} else if (location. getLocType () = BDLocation. typeServerError) {sb. append ("\ ndescribe:"); sb. append ("server network positioning failed, Can feedback IMEI number and big body positioning time to the loc-bugs@baidu.com, someone will trace the cause");} else if (location. getLocType () = BDLocation. typeNetWorkException) {sb. append ("\ ndescribe:"); sb. append ("failed to locate due to different networks, please check if the network is smooth");} else if (location. getLocType () = BDLocation. typeCriteriaException) {sb. append ("\ ndescribe:"); sb. append. append ("\ nlocationdescribe:"); sb. append (location. getLocationDescribe (); // location semantic information List
 
  
List = location. getPoiList (); // POI data if (list! = Null) {sb. append ("\ npoilist size =:"); sb. append (list. size (); for (Poi p: list) {sb. append ("\ npoi =:"); sb. append (p. getId () + "" + p. getName () + "" + p. getRank () ;}} Log. I ("BaiduLocationApiDem", sb. toString ());}
 

 

The BDLocation class encapsulates the Positioning Result of the positioning SDK, which is obtained in the onReceive method of BDLocationListener. Users of this type can obtain information such as error code, coordinates of locations, and precision radius. For more information, see class reference.

Get error code:


public int getLocType ( )

Return Value:

61: GPS Positioning Result. GPS positioning is successful.

62: An error occurred while locating the device. Check whether the carrier network or Wi-Fi network is enabled and try again.

63: network exception. failed to initiate a request to the server. Please check whether the mobile phone network is smooth and try again to locate the request.

65: locate the cache results.

66: offline location result. Return results when calling requestOfflineLocaiton.

67: offline location failed. Return results when calling requestOfflineLocaiton.

68: when the network connection fails, find the corresponding results when the local offline location is located.

161: Network Positioning Result. Network Positioning is successful.

162: request string ciphertext parsing failed. This is generally caused by loading the SO file on the client. Please refer to the Development Guide or demo for development in strict accordance with the corresponding SO file.

167: failed to locate the server. Please check whether the permission to obtain location information is disabled and try again.

502: the key parameter is incorrect. please reapply for the KEY according to the instructions.

505: The key does not exist or is invalid. Please follow the instructions to apply for a new KEY.

601: The key service is disabled by the developer. Please follow the instructions to apply for a new KEY.

602: the key mcode does not match. The security code is incorrect during the ak configuration. Make sure that the sha1 is correct and the semicolon (;) is in English; the package name is the package name of your current application. please reapply for the KEY according to the instructions.

501 ~ 700: key Verification Failed. Please follow the instructions to apply for a new KEY.

If not, please remember this return value, and to Baidu LBS Open Platform Forum Andriod positioning SDK Forum exchange http://bbs.lbsyun.baidu.com/forum.php? Mod = forumdisplay & fid = 10. If the returned value is 162 ~ 167. Please feed the error code, imei, and positioning time to the loc-bugs@baidu.com so that we can track down the problem.

Step 4: start positioning

 


mLocationClient.start();

Start: start the positioning SDK. Stop: Disable the SDK. After you call start, you only need to wait for the automatic callback of the positioning result.

The developer can locate the scenario in a single time, and then directly call the stop function after receiving the positioning result.

If you still want to locate the position after stopping, you can start again and wait for the positioning result to be called back.

If you want to locate the location based on your own logic request, you can request the locationclient. requestLocation () function based on your own logic after start. It will trigger the internal location logic of the positioning SDK and wait for the location callback.

Location reminder

The location reminder can be sent three times at most, and will not be sent after three times. If you need to remind you again or modify the coordinates of the reminder point, you can use the setpolicylocation () function.

// The location reminder code Myer yer = new NotifyLister (); mNotifyer. setNotifyLocation (42.03249652949337, 113.3129895882556, 3000, "gps"); // The four parameters represent the coordinates of the points to be reminded. The specific meanings are as follows: latitude, longitude, distance range, coordinate System Type (gcj02, gps, bd09, bd09ll) mLocationClient. registerNotify (Myer YER); // After registering a location reminder listener event, you can use setpolicylocation to modify the location reminder settings, which takes effect immediately after modification. // BDNotifyListner implements public class NotifyLister extends BDNotifyListener {public void onNotify (BDLocation mlocation, float distance) {mVibrator01.vibrate (1000 ); // The vibration reminder has reached the specified position} // cancel the location reminder mLocationClient. removeNotifyEvent (mNotifyer );

 

Iv. Personal Understanding

The relationship between the three classes is also very easy to understand through the description in the third part.

As the core SDK class, the LocationClient class manages and operates the positioning service, such as enabling and stopping the positioning service;

The LocationClientOption class is the configuration information class. It sets the configuration information of the positioning service, such as the positioning time interval and whether to use GPS;

The BDLocationListener interface can obtain the positioning data, which can process or store the positioning data;

There may be many problems in the process of positioning, such as not displaying a map, not locating, not entering the callback function, etc. There are various methods on the Internet, but can I solve my own problems? Not necessarily. Check the API_KEY, check whether the LocationClient is declared in the main thread, and so on. Another reason is that the Baidu map positioning SDK is updated very quickly. classes that can be found in 15 years may already be overwritten, so we can't do it. The best way is to port Baidu's Demo.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.