(Baidu Map API) V4-2 version positioning function

Source: Internet
Author: User

these days in the Guo Lin teacher's masterpiece, Baidu map This card for a long time, the reason is because Baidu update iteration speed too fast, resulting in the teacher's version of the book has been eliminated and eliminated, but still gave me a lot of inspiration AH. Tonight, I realized the positioning function of Baidu map.

Baidu Map API of what, also do not say more. Official online Introduction is also more detailed, are also Chinese, carefully read down on the line, to, I use the v4-2 version. Feel only 11 o'clock after the work efficiency will be doubled ah, we have not this experience ah, recently want to do a running software, of course, is very simple kind, finished will paste the code and everyone to discuss.

Website Link: http://developer.baidu.com/map/index.php?title=android-locsdk/guide/v4-2



Package com.nsz.baidulocationtest;/** * Location Service interface *  * @author zhou.ni *  */public interface Locationserviceinterface {/** * initialize */void init ();/** * Start positioning */void startlocation ();/** * Stop positioning */void Stop ();}

Package Com.nsz.baidulocationtest;import Android.content.context;import Android.location.location;import Android.util.log;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;/** * provides location service implementation * * @author Zhou.ni * */public class Baidulocations Ercice implements Locationserviceinterface {private static final String TAG = "Locationutilbaidu";//private static Final I NT Mlocationupdatemintime = 20000; Locating request Interval Private locationclient mlocationclient = null;private Bdlocationlistener mbdlocationlistener;public location Location;private String Tempcoor = "gcj02";  coordinate system private Locationmode Tempmode = locationmode.hight_accuracy; High precision positioning mode context Mcontext;public Baidulocationsercice (context Mcontext) {super (); this.mcontext = Mcontext;init ();} public void init () {mlocationclient = new locationclient (mcontext); SetOption ();} /** * Set the listener after positioning is complete * @param listener */public void Registerlocationlistenner (Bdlocationlistener listener) { This.mbdlocationlistener = Listener;mlocationclient.registerlocationlistener (Mbdlocationlistener);} /** * Get the last location result * * @return */public bdlocation getlastlocation () {return mlocationclient.getlastknownlocation ();} /** * Configure positional parameters */private void SetOption () {locationclientoption option = new Locationclientoption (); Option.setlocationmode (tempmode);//Set positioning mode Option.setcoortype (Tempcoor);//Return the positioning result is Baidu latitude and longitude, the default value of Gcj02//option.setscanspan ( Mlocationupdatemintime);//sets the time interval for initiating a location request. Do not set to locate only once option.setisneedaddress (true); The returned positioning result contains address information option.setneeddevicedirect (TRUE);//The positioning result returned contains the direction of the phone head mlocationclient.setlocoption (option); @Overridepublic void Startlocation () {if (mlocationclient! = null) {Mlocationclient.start (); Mlocationclient.requestlocation ();}} @Overridepublic void Stop () {if (mlocationclient! = null && mlocationclient.isstarted ()) {Mlocationclient.stop ( );}} Private Bdlocation Mlocation;///**//* Implement real bit callback listener//*///public class Mylocationlistenner implements Bdlocationlistener {////@Override//public void Onreceivelocation (bdlocation location) {//if (location = = null)//return;////Receive Location//stringbuffer S b = new StringBuffer,//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.getlongitude ());//sb.append (" \nradius: ");//sb.append (Location.getradius ()) ;//if (location.getloctype () = = bdlocation.typegpslocation) {//sb.append ("\nspeed:");//sb.append (location.getSpeed ());//sb.append ("\nsatellite:");//sb.append (Location.getsatellitenumber ());//sb.append ("\ndirection:");// Sb.append ("\naddr:");//sb.append (Location.getaddrstr ());//sb.append (Location.getdirection ());/} else if ( Location.getloctype () = = bdlocation.typenetworklocation) {//sb.append ("\naddr:");//SB. Append (Location.getaddrstr ());////operator Information//sb.append ("\noperationers:");//sb.append (Location.getoperators ());// }//LOG.I (TAG, sb.tostring ());//if (location = null) {//mlocation = location;//}////}////}}

Package Com.nsz.baidulocationtest;import Java.util.timer;import Java.util.timertask;import Com.baidu.location.bdlocation;import Com.baidu.location.bdlocationlistener;import Android.app.Activity;import Android.os.bundle;import Android.widget.textview;public class Addrlocationactivity extends Activity {private Baidulocationsercice mbaidulocationsercice;private Mylocitionlistener Locationlistener; TextView TV; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_addr_search); Initview ();} private void Initview () {TV = (TextView) This.findviewbyid (r.id.tv); mbaidulocationsercice = new Baidulocationsercice ( Getapplicationcontext ()); GetLocation ();} private void GetLocation () {try {if (Locationlistener = = null) {Locationlistener = new Mylocitionlistener (); mbaidulocatio Nsercice.registerlocationlistenner (Locationlistener);} Mbaidulocationsercice.startlocation ();//Start Positioning timeouttimer.schedule (New Locationtimeouttask (), 15000);//15-second Timeout} catch (Exception e) {if (e!=null) E.printstacktrace ();}} Class Mylocitionlistener implements bdlocationlistener{@Overridepublic void Onreceivelocation (Bdlocation locition) { if (locition = = null) {return;}        Mbaidulocationsercice.stop (); Timeouttimer.cancel ();                Islocationreturn = true;         MyAddress addr = transform (locition);                        Tv.settext (Addr.getaddrname ()); }}/** * Object Conversion * @param location * @return */private MyAddress transform (bdlocation location) {MyAddress add R = new MyAddress (); Addr.setaddrname (Location.getaddrstr ()); Addr.setcityname (Location.getcity ()); Addr.setlat (    Location.getlatitude () + ""); Addr.setlng (Location.getlongitude () + ""); return addr; }protected Boolean islocationreturn = false;private Timer Timeouttimer = new timer (); class Locationtimeouttask extends Tim ertask{@Overridepublic void Run () {if (!islocationreturn) {if (Mbaidulocationsercice! = null) { Mbaidulocationsercice.stop ();}}}}

Package Com.nsz.baidulocationtest;import java.io.serializable;/** * Address model *  * @author zhou.ni *  */public class  MyAddress implements Serializable {private static final long Serialversionuid = 1l;/** verbose address **/private String addrname;/** Address city name **/private string cityname;/** address latitude **/private string lat;/** address longitude **/private string Lng;public string GetAd Drname () {return addrname;} public void Setaddrname (String addrname) {this.addrname = Addrname;} Public String Getcityname () {return cityname;} public void Setcityname (String cityname) {this.cityname = CityName;} Public String Getlat () {return lat;} public void Setlat (String lat) {This.lat = lat;} Public String getlng () {return LNG;} public void Setlng (String lng) {this.lng = LNG;}}

<manifest xmlns:android= "http://schemas.android.com/apk/res/android" package= "Com.nsz.baidulocationtest" Android:versioncode= "1" android:versionname= "1.0" > <uses-sdk android:minsdkversion= "8" Android: targetsdkversion= "/> <uses-permission android:name=" Android.permission.ACCESS_COARSE_LOCATION "> </ uses-permission> <uses-permission android:name= "Android.permission.ACCESS_FINE_LOCATION" > </ uses-permission> <uses-permission android:name= "Android.permission.ACCESS_WIFI_STATE" > </ uses-permission> <uses-permission android:name= "Android.permission.ACCESS_NETWORK_STATE" > </ uses-permission> <uses-permission android:name= "Android.permission.CHANGE_WIFI_STATE" > </ uses-permission> <uses-permission android:name= "Android.permission.READ_PHONE_STATE" > </ uses-permission> <uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"> </uses-permission> <uses-permission android:name=" Android.permission.INTERNET "/> <uses-per Mission android:name= "Android.permission.MOUNT_UNMOUNT_FILESYSTEMS" > </uses-permission> < Uses-permission android:name= "Android.permission.READ_LOGS" > </uses-permission> <uses-permission Andro Id:name= "Android.permission.VIBRATE"/> <uses-permission android:name= "Android.permission.WAKE_LOCK"/> &L T;uses-permission android:name= "Android.permission.WRITE_SETTINGS"/> <application android:allowba Ckup= "true" android:icon= "@drawable/ic_launcher" android:label= "@string/app_name" Android:theme= "@sty Le/apptheme "> <service android:name=" com.baidu.location.f "android:enabled=" tr UE "android:process=": remote > <intent-filter> <action android:name= "com      . baidu.location.service_v2.2 ">          </action> </intent-filter> </service> <!--Meta-data needs to be written in Applicatio N---<meta-data android:name= "Com.baidu.lbsapi.API_KEY" android:value= "dupr6inxeqagj9            Aln2qgjxy7 "/> <activity android:name=" com.nsz.baidulocationtest.AddrLocationActivity " Android:label= "@string/app_name" > <intent-filter> <action android:name= "Android.int Ent.action.MAIN "/> <category android:name=" Android.intent.category.LAUNCHER "/> </i Ntent-filter> </activity> </application></manifest>

The layout file is not affixed to the code, it is a textview. Yes, I do not know why, I have a Huawei Z87, there is no SM card, but connected to the WiFi, but can not locate the success. But another hammer to go can, if you know, please tell.


(Baidu Map API) V4-2 version positioning function

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.