android-Baidu Map Direction sensing and mode changes

Source: Internet
Author: User

Target effect:

Set several modes in the menu, click to see different map forms, and cut a few pictures here.


1. First go to Baidu map website http://lbsyun.baidu.com/


2. After registering the account, click on the development->android map sdk-> Get the key, enter to display the following page.


3. Create an App


4. Open Eclipse, select Window->preferences->android->build, Get SHA1


5. After submission go back to the previous Android Map SDK page Select the relevant download, then click on Custom Download


6. Select Location function, base map, search function, lbs cloud search, calculate tool, click Development Package, sample code and class reference to download according to your actual situation


7. Unzip after download is complete


8. Start creating apps, note the package name when creating


9. Once created, copy all content from the Libs directory you just downloaded to the Project Libs folder.


10. Start writing code. Activity_main.xml page into a map control.

Activity_main.xml page:

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android"    xmlns:tools= "http// Schemas.android.com/tools "    android:layout_width=" match_parent "    android:layout_height=" Match_parent "    tools:context= ". Mainactivity "><com.baidu.mapapi.map.mapview      android:id=" @+id/mv_map "      android:layout_width=" Fill_ Parent "      android:layout_height=" fill_parent "      android:clickable=" true "/></relativelayout>

11.main.xml as a menu page, add several mode selections.

Main.xml page:

<menu xmlns:android= "Http://schemas.android.com/apk/res/android" > <item android:id= "@+id/id_map_common        "Android:orderincategory=" android:showasaction= "Never" android:title= "General map"/> <item Android:id= "@+id/id_map_site" android:orderincategory= "android:showasaction=" Never "Android : title= "satellite map"/> <item android:id= "@+id/id_map_traffic" android:orderincategory= "Android" : showasaction= "Never" android:title= "real-time traffic (off)"/> <item android:id= "@+id/id_map_location" an droid:orderincategory= "android:showasaction=" Never "android:title=" my Location "/> <item Androi D:id= "@+id/id_map_mode_common" android:orderincategory= "android:showasaction=" Never "Android:tit" le= "Normal mode"/> <item android:id= "@+id/id_map_mode_following" android:orderincategory= "Android" Oid:showasaction= "Never"        Android:title= "follow mode"/> <item android:id= "@+id/id_map_mode_compass" android:orderincategory= "Android:showasaction=" "Never" android:title= "Compass Mode"/></menu>


12. Create a Myorientationlistener.java page to get it when the direction changes. Myorientationlistener.java page:
Package Com.imooc.baidumap;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 Sensormanager msensormanager;private Context Context;private sensor msensor;//Sensors private float lastx;public myorientationlistener (context context) { This.context = context;} Turn on monitoring @suppresswarnings ("deprecation") public void Start () {//Get system service msensormanager= (Sensormanager) Context.getsystemservice (Context.sensor_service); if (msensormanager!=null) {//Get direction sensor msensor= Msensormanager.getdefaultsensor (sensor.type_orientation);} if (msensor!=null) {Msensormanager.registerlistener (this, msensor,sensormanager.sensor_delay_ui);//The third parameter is longitude}}// End Listener public void Stop () {//Stop positioning msensormanager.unregisterlistener (this);} When longitude changes, @overridepublic void onaccuracychanged (Sensor arg0, int arg1) {}//void @overridepublic when latitude changes)Nged (Sensorevent event) {//If the type returned by the event is the direction sensor if (Event.sensor.getType () ==sensor.type_orientation) {float x= event.values[sensormanager.data_x];//If the change is greater than once if (Math.Abs (X-LASTX) >1.0) {//notifies the main interface to go back if (monorientationlistener !=null) {monorientationlistener.onorientationchanged (x);}} Lastx=x;}} Private Onorientationlistener monorientationlistener;public void Setmonorientationlistener (OnOrientationListener Monorientationlistener) {this.monorientationlistener = Monorientationlistener;} Return interface public interface onorientationlistener{void onorientationchanged (float x);}}


13. The main page Mainactivity.java pages for mode changes and positioning. Mainactivity.java page:
Package Com.imooc.baidumap;import Com.baidu.location.bdlocation;import Com.baidu.location.BDLocationListener; Import Com.baidu.location.locationclient;import Com.baidu.location.locationclientoption;import Com.baidu.location.locationclientoption.locationmode;import Com.baidu.mapapi.sdkinitializer;import Com.baidu.mapapi.map.baidumap;import Com.baidu.mapapi.map.bitmapdescriptor;import Com.baidu.mapapi.map.bitmapdescriptorfactory;import Com.baidu.mapapi.map.mylocationconfiguration;import Com.baidu.mapapi.map.mapstatusupdate;import Com.baidu.mapapi.map.mapstatusupdatefactory;import Com.baidu.mapapi.map.mapview;import Com.baidu.mapapi.map.mylocationconfiguration;import Com.baidu.mapapi.map.mylocationdata;import Com.baidu.mapapi.model.latlng;import Com.imooc.baidumap.myorientationlistener.onorientationlistener;import Android.os.bundle;import Android.app.activity;import Android.view.menu;import Android.view.menuitem;import Android.view.Window;public class Mainactivity extends Activity {private Mapview mv_map;private baidumap baidumap;//location related private locationclient mlocationclient;private MyLocationListener Mlocationlistener;private Boolean isfirstin = True;private double mlatitude; Record the latest latitude and longitude private double mlongtitude;//custom positioning icon Private Bitmapdescriptor miconlocation;private Myorientationlistener morientationlistener;private float mcurrentx;//mode variable private Com.baidu.mapapi.map.MyLocationConfiguration.LocationMode mlocationmode; @Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate);//Initialize the context information before using each component of the SDK and pass in the applicationcontext// Note that this method is to be implemented before Setcontentview method Sdkinitializer.initialize (Getapplicationcontext ()); Setcontentview (r.layout.activity _main);//Initialize Control init ();//Initialize positioning initlocation ();} Initialize the control private void init () {Mv_map = (Mapview) Findviewbyid (r.id.mv_map); baidumap = Mv_map.getmap (); Mapstatusupdate MSU = Mapstatusupdatefactory.zoomto (15.0f);//set map magnification baidumap.setmapstatus (MSU);} @Overrideprotected void OnStart () {Super.onstart (); Baidumap. setmylocationenabled (True); if (!mlocationclient.isstarted ()) {//Open positioning Mlocationclient.start ();// Open Direction sensor Morientationlistener.start ();}} @Overrideprotected void OnStop () {super.onstop (); baidumap.setmylocationenabled (false);//Stop Positioning mlocationclient.stop ( );//Stop Direction Sensor morientationlistener.stop ();} @Overrideprotected void Onresume () {super.onresume ();//execute Mmapview when activity executes Onresume. Onresume () for map lifecycle management mv_ Map.onresume ();} @Overrideprotected void OnPause () {super.onpause ();//execute Mmapview when activity executes OnPause. OnPause () for map lifecycle management mv_ Map.onpause ();} @Overrideprotected void OnDestroy () {Super.ondestroy ();//Perform Mmapview.ondestroy () during activity execution OnDestroy to implement the map lifecycle management MV _map.ondestroy ();} @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {getmenuinflater (). Inflate (R.menu.main, menu); return Super.oncreateoptionsmenu (menu);} Click menu to toggle Map @overridepublic boolean onoptionsitemselected (MenuItem item) {switch (Item.getitemid ()) {case R.id.id_map _common://General Map Baidumap.setmaptype (baidumap.map_type_normal); BreaK;case r.id.id_map_site://Satellite map Baidumap.setmaptype (baidumap.map_type_satellite); Break;case R.id.id_map_traffic:// Real-time traffic if (baidumap.istrafficenabled ()) {baidumap.settrafficenabled (false); Item.settitle ("Live Traffic (off)");} else { Baidumap.settrafficenabled (True); Item.settitle ("Live Traffic (On)");} Break;case R.id.id_map_location:centertomylocat (); Break;case R.id.id_map_mode_common:mlocationmode = Com.baidu.mapapi.map.mylocationconfiguration.locationmode.normal;break;case R.id.id_map_mode_following: Mlocationmode = Com.baidu.mapapi.map.mylocationconfiguration.locationmode.following;break;case R.id.id_map_mode_ Compass:mlocationmode = Com.baidu.mapapi.map.mylocationconfiguration.locationmode.compass;break;default:break;} return super.onoptionsitemselected (item);} Navigate to my Location private void Centertomylocat () {latlng latlng = new Latlng (mlatitude, mlongtitude); Mapstatusupdate MSU = MAPSTATUSUPDATEFACTORY.NEWLATLNG (LATLNG); Baidumap.animatemapstatus (MSU);} Private class Mylocationlistener implements Bdlocationlistener {@Overridepublic void onreceivelocation (bdlocation location) {Mylocationdata data = new Mylocationdata.builder ()//. Direction (Mcurrentx)//.accuracy (Location.getradius ())//.latitude (Location.getlatitude ())//.longitude ( Location.getlongitude ())//.build (); baidumap.setmylocationdata (data);//update Location mlatitude = Location.getlatitude (); Mlongtitude = Location.getlongitude ();//Determine if the first entry into if (Isfirstin) {latlng latlng = new Latlng (Location.getlatitude (), Location.getlongitude ()); Mapstatusupdate MSU = MAPSTATUSUPDATEFACTORY.NEWLATLNG (LATLNG); Baidumap.animatemapstatus (MSU); isFirstIn = false;} Set custom icon mylocationconfiguration config = new Mylocationconfiguration (Mlocationmode, True, miconlocation); Baidumap.setmylocationconfigeration (config);}} Initialize location private void Initlocation () {Mlocationmode = Com.baidu.mapapi.map.MyLocationConfiguration.LocationMode.NORMAL; Default mode mlocationclient = new Locationclient (this); Mlocationlistener = new Mylocationlistener (); Mlocationclient.registerlocationlistener (mlocationListener); locationclientoption option = new Locationclientoption (); Option.setcoortype ("bd0911"); Option.setisneedaddress (True ); Option.setopengps (true); Option.setscanspan (1000);//How many seconds each request mlocationclient.setlocoption (option);// Initialize icon miconlocation = Bitmapdescriptorfactory.fromresource (r.drawable.arrow); morientationlistener = new Myorientationlistener (this); Morientationlistener.setmonorientationlistener (new Onorientationlistener () {@ overridepublic void onorientationchanged (float x) {mcurrentx = x;}});}}


14.androidmanifest.xml page configuration permissions and add Appkey. Androidmanifest.xml page:
<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http://schemas.android.com/apk/res/        Android "package=" Com.imooc.baidumap "android:versioncode=" 1 "android:versionname=" 1.0 "> <uses-sdk android:minsdkversion= "android:targetsdkversion="/> <uses-permission android:name= "android.perm Ission. Access_network_state "/> <uses-permission android:name=" Android.permission.INTERNET "/> <uses-permissio n android:name= "Com.android.launcher.permission.READ_SETTINGS"/> <uses-permission android:name= " Android.permission.WAKE_LOCK "/> <uses-permission android:name=" Android.permission.CHANGE_WIFI_STATE "/> & Lt;uses-permission android:name= "Android.permission.ACCESS_WIFI_STATE"/> <uses-permission android:name= " Android.permission.GET_TASKS "/> <uses-permission android:name=" Android.permission.WRITE_EXTERNAL_STORAGE "/ > <uses-permission android:name= "Android.permission.WRIte_settings "/> <uses-permission android:name=" Android.permission.READ_PHONE_STATE "/> <application Android:allowbackup= "true" android:icon= "@drawable/ic_launcher" android:label= "@string/app_name" a Ndroid:theme= "@style/apptheme" > <meta-data android:name= "Com.baidu.lbsapi.API_KEY" and Roid:value= "3KJZS5YM9TXSM98V7BVJWZTZWAOAJSGP"/><!--Create app Appkey--<activity android:name=                "Com.imooc.baidumap.MainActivity" android:label= "@string/app_name" > <intent-filter> <action android:name= "Android.intent.action.MAIN"/> <category android:name= "Android.inte Nt.category.LAUNCHER "/> </intent-filter> </activity> <service A            Ndroid:name= "COM.BAIDU.LOCATION.F" android:enabled= "true" android:process= ": Remote" > <intent-filteR><action android:name= "com.baidu.location.service_v2.2" > </action> </inte Nt-filter> </service> </application></manifest>



15. The program runs to show the target effect.





android-Baidu Map Direction sensing and mode changes

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.