Android Baidu map SDK v3.0.0 (2) Positioning and integration with direction sensors, androidv3.0.0

Source: Internet
Author: User

Android Baidu map SDK v3.0.0 (2) Positioning and integration with direction sensors, androidv3.0.0

Reprinted please indicate the source: http://blog.csdn.net/lmj623565791/article/details/37730469

In the previous blog, we successfully imported the map into our project. In this article, we are going to add a map: first, the positioning function; second, combined with the direction sensor, to confirm the direction of the road by rotating the mobile phone. With these two functions, the map can already serve me ~~~~

:


Okay, you can run the Code. For convenience, I put all the buttons in the menu.

1. Start positioning for the first time

/*** Locate the client */private LocationClient mLocationClient;/*** locate the listener */public MyLocationListener mMyLocationListener; /*** current locating mode */private LocationMode mCurrentMode = LocationMode. NORMAL;/***** whether it is the first time to locate */private volatile boolean isFristLocation = true;/***** initialize the locating code */private void initMyLocation () {// locate and initialize mLocationClient = new LocationClient (this); mMyLocationListener = new MyLocationListener (); mLocationClient. registerLocationListener (mMyLocationListener); // you can specify the LocationClientOption option for locating. setOpenGps (true); // enable gpsoption. setCoorType ("bd09ll"); // sets the coordinate type option. setScanSpan (1000); mLocationClient. setLocOption (option );}

Then the listener MyLocationListener is located:
/*** Implement real-time callback listener */public class MyLocationListener implements BDLocationListener {@ Overridepublic void onReceiveLocation (BDLocation location) {// After map view is destroyed, if (location = null | mMapView = null) return is not processed at the newly received location; // construct the location data MyLocationData locData = new MyLocationData. builder (). accuracy (location. getRadius () // set the direction information obtained by the developer, clockwise 0-360.direction (mXDirection ). latitude (location. getLatitude ()). longpolling (location. getlongpolling ()). build (); mCurrentAccracy = location. getRadius (); // you can specify mBaiduMap. setMyLocationData (locData); mCurrentLantitude = location. getLatitude (); mcurrentlongdistance = location. getlongpolling (); // set the custom icon BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory. fromResource (R. drawable. navi_map_gps_locked); MyLocationConfigeration config = new MyLocationConfigeration (mCurrentMode, true, mCurrentMarker); mBaiduMap. setMyLocationConfigeration (config); // when positioning for the first time, move the map location to the current location if (isFristLocation) {isFristLocation = false; LatLng ll = new LatLng (location. getLatitude (), location. getlongpolling (); MapStatusUpdate u = MapStatusUpdateFactory. newLatLng (ll); mBaiduMap. animateMapStatus (u );}}}
We can see that we initialized the positioning parameters and set the positioning listener. The location will be located once every 1 s. When the application is opened, the first location will set the map center to the current user location.
Positioning is also relatively power-consuming, So we enable positioning in onStart and disable positioning in onStop ~~ In this way, when the application is minimized, no GPS request is always located. If the user sees that your app has been located, it is estimated that it will be immediately uninstalled ~

@ Overrideprotected void onStart () {// enable Layer positioning mBaiduMap. setMyLocationEnabled (true); if (! MLocationClient. isStarted () {mLocationClient. start ();} // enable the direction sensor myOrientationListener. start (); super. onStart () ;}@ Overrideprotected void onStop () {// close the layer to locate mBaiduMap. setMyLocationEnabled (false); mLocationClient. stop (); // turn off the direction sensor myOrientationListener. stop (); super. onStop ();}

The above sensor code will be introduced later ~

Remember to configure a service in AndroidManifest. xml

  <service            android:name="com.baidu.location.f"            android:enabled="true"            android:process=":remote" >            <intent-filter>                <action android:name="com.baidu.location.service_v2.2" >                </action>            </intent-filter>        </service>

Now the basic positioning function has been implemented ~ However, we also need to add the positioning button and the direction sensor.

2. My location

Click my location to call the center2myLoc method.

case R.id.id_menu_map_myLoc:center2myLoc();break;

/*** The map is moved to my location. You can send a new location request and then locate it. * directly obtain the last latitude and longitude. If the location is not located for a long time, it may show poor results */private void center2myLoc () {LatLng ll = new LatLng (mCurrentLantitude, mcurrentlong.pdf); MapStatusUpdate u = MapStatusUpdateFactory. newLatLng (ll); mBaiduMap. animateMapStatus (u );}

We have saved the last positioning longitude and latitude in the positioning listener, so you only need to click and move the map to the corresponding position.

3. Integrated direction Sensor

The first is the encapsulated class of the direction sensor MyOrientationListener. java

Package com. zhy. zhy_baidu_ditu_demo00; import android. content. context; import android. hardware. sensor; import android. hardware. sensorEvent; import android. hardware. sensorEventListener; import android. hardware. sensorManager; public class MyOrientationListener implements SensorEventListener {private Context context; private SensorManager sensorManager; private Sensor sensor; private float lastX; private OnOri EntationListener onOrientationListener; public MyOrientationListener (Context context) {this. context = context;} // start public void start () {// obtain sensor manager sensorManager = (SensorManager) context. getSystemService (Context. SENSOR_SERVICE); if (sensorManager! = Null) {// obtain the direction sensor Sensor = sensorManager. getdefasensensor (sensor. TYPE_ORIENTATION);} // register if (sensor! = Null) {// SensorManager. SENSOR_DELAY_UIsensorManager.registerListener (this, sensor, SensorManager. SENSOR_DELAY_UI) ;}}// stop public void stop () {sensorManager. unregisterListener (this) ;}@ Overridepublic void onAccuracyChanged (Sensor sensor, int accuracy) {}@ Overridepublic void onSensorChanged (SensorEvent event) {// accept the type of the direction Sensor if (event. sensor. getType () = Sensor. TYPE_ORIENTATION) {// here we can get the data and process float x = event as needed. values [SensorManager. DATA_X]; if (Math. abs (x-lastX) & gt; 1.0) {onOrientationListener. onOrientationChanged (x);} // Log. e ("DATA_X", x + ""); lastX = x ;}} public void setOnOrientationListener (OnOrientationListener onOrientationListener) {this. onOrientationListener = onOrientationListener;} public interface OnOrientationListener {void onOrientationChanged (float x );}}

Initialize the direction sensor in onCreate

/*** Initialize the direction sensor */private void initOritationListener () {myOrientationListener = new MyOrientationListener (getApplicationContext (); myOrientationListener. setOnOrientationListener (new OnOrientationListener () {@ Overridepublic void onOrientationChanged (float x) {mXDirection = (int) x; // construct the positioning data MyLocationData locData = new MyLocationData. builder (). accuracy (mCurrentAccracy) // set the direction information obtained by the developer, clockwise 0-360.direction (mXDirection ). latitude (mCurrentLantitude ). longpolling (mcurrentlongpolling ). build (); // you can specify mBaiduMap. setMyLocationData (locData); // sets the custom icon BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory. fromResource (R. drawable. navi_map_gps_locked); MyLocationConfigeration config = new MyLocationConfigeration (mCurrentMode, true, mCurrentMarker); mBaiduMap. setMyLocationConfigeration (config );}});}

Enable and disable the direction sensor in onStart and onStop respectively.

The orientation of the mobile phone is determined by actually using

New MyLocationData. Builder () // set the direction information obtained by the developer, clockwise 0-360. direction (mXDirection)
You only need to set the angle in the x direction ~~~ Is it easy ~~~


Now, the introduction is complete. We will not introduce the switching of map styles and the switching of following and compass modes. Let's take a look at the source code ~~


Download source code





I made an android app. The app has a secondary function, which can be map positioning. It uses AMAP APIs. I want to start the app first.

Like map positioning, you should use service...
Enable a service when you open the program, and then enable map location locating in the service.
 
Where can I find my android api?

Want to see all the APIS? Many android experts may not be able to do this. Api is a reference. The key is to know what the api will have. Just like learning java, it is impossible to learn all the APIs. You can only guess which class has any method when using it. Hope to help you.

Related Article

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.