Baidu Positioning SDK Use V4.0

Source: Internet
Author: User
Tags cos error handling pow sin time interval valid xmlns stringbuffer

Preface: Recently in doing an application, to use the LBS location, this would like to write their own, but the technology is not in place, and time is not much, or the first to achieve the main bar, and then the study of the location of the lbs, Google also has lbs location services, but the total feeling of Google's great God was rushed to Hong Kong, has been Do not know how lbs, estimated also not, so directly with the Baidu positioning SDK, but Baidu's positioning SDK daily maximum traffic is 10W, so the software users, or write the positioning code it, like me in the early use also does not matter, after all, the pre-user volume is not so big.

Related instructions:

According to the "Baidu Positioning SDK Development Guide", It said in V4.0 after all to apply key, but now the key application has been quite complex, became the root application related, grandma a bear, I have been thinking for a long time do not know the right to apply, but I in the program to remove key, still can be positioned, I do not know if this is required key or not need key. The guide says that when a map is initialized, it uses key, which may also indicate that no key is needed for pure positioning. Since you don't need a key, you can't limit the number of times you use it. Haha, as if I had found something. Since do not need key, but the source code is to add Setkey () This sentence, and many people in the forum said the problem of setting key error (Http://bbs.lbsyun.baidu.com/viewthread.php?tid=2859&extra =PAGE%3D1), I this machine success is very not practical ah. =_=. I. Related INFORMATION

"Baidu Positioning SDK Development Guide": http://developer.baidu.com/map/geosdk-android-developv4.0.htm

"Android use Baidu Positioning SDK method and error Handling": http://mobile.51cto.com/aprogram-376690.htm (This article is good, the location of the interface encapsulated into a class, directly call on it)

"Why can't my program be located": http://bbs.lbsyun.baidu.com/viewthread.php?tid=557&extra=page%3D1 Second, the realization of positioning

Effect Diagram:

1, guide the library file

Download the latest library file in the related. Copy the liblocsdk4.so file to the Libs/armeabi directory. Copy the Locsdk4.0.jar file to the project's Libs directory and select "Add JARs" in the project properties->java Build path->libraries, selecting Locsdk4.0.jar, and returning after determining. This allows you to use the Baidu geo-fence SDK in your program. 2. Set Androidmanifest.xml 2.1. Declare service components in the Application tab, each with its own individual location service

<service android:name= "COM.BAIDU.LOCATION.F" android:enabled= "true" android:process= ": Remote" > </service > 2.2 Declaring usage rights
<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-permission android:name= " Android.permission.MOUNT_UNMOUNT_FILESYSTEMS "></uses-permission> <uses-permission android:name=" Android.permission.READ_LOGS "></uses-permission> 3. XML Content
<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 "
    android:paddingbottom= "@dimen/activity_vertical_margin"
    android:paddingleft= "@dimen/activity_ Horizontal_margin "
    android:paddingright=" @dimen/activity_horizontal_margin "
    android:paddingtop=" @dimen /activity_vertical_margin "
    tools:context=". Mainactivity ">
    
    <textview
        android:id=" @+id/textview "
        android:layout_width=" Fill_parent "
        android:layout_height= "wrap_content"
        android:textcolor= "#ff00ff" >
    </TextView>

	<button 
	    android:id= "@+id/relbs_button"
	    android:layout_width= "fill_parent"
	    android:layout_ height= "Wrap_content"
	    android:layout_below= "@+id/textview"
	    android:text= "reposition"/> </

Relativelayout>
4, Java page
Package Com.example.try_lbs_baidu;
/** * Try Baidu Positioning SDK * @author Harvic * @date 2013-12-28 * * Import android.app.Activity;
Import Android.os.Bundle;
Import Android.util.Log;
Import Android.view.View;
Import Android.widget.Button;

Import Android.widget.TextView;
Import com.baidu.location.BDLocation;
Import Com.baidu.location.BDLocationListener;
Import com.baidu.location.LocationClient;

Import com.baidu.location.LocationClientOption;
	public class Mainactivity extends Activity {private TextView mTv = null;
	Public locationclient mlocationclient = null;
	Public Mylocationlistenner MyListener = new Mylocationlistenner ();
	Public Button Relbsbutton=null;


	public static String TAG = "MSG";
		@Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
		
		Setcontentview (R.layout.activity_main);
		MTv = (TextView) Findviewbyid (R.id.textview);
		
		relbsbutton= (Button) Findviewbyid (R.id.relbs_button);

	Mlocationclient = new Locationclient (this);	/** —————————————————————————————————————————————————————————————————— * Here AK and apply signature package name bindings, if used in your own project need to replace the key that you applied for yourself * —————————————————————————————————————————————————————————————————— *//Mlocationclient.setak ("	 
697f50541f8d4779124896681cb6584d ");
		Mlocationclient.setak ("Z4nqerrqxnhnzt5vognvrt80");

		Mlocationclient.registerlocationlistener (MyListener); Setlocationoption ();//Set positioning Parameters Mlocationclient.start ();//start positioning//Reposition Relbsbutton.setonclicklistener (new Button. Onclicklistener () {public void OnClick (View v) {//TODO auto-generated Method stub if (mlocationclient! = nul
				L && mlocationclient.isstarted ()) mlocationclient.requestlocation ();
			else Log.d ("msg", "locclient is null or not started");
		
	}
		});
		}//Set related parameters private void Setlocationoption () {locationclientoption option = new Locationclientoption ();
		Option.setopengps (TRUE); Option.setaddrtype ("all");//The locating result returned contains the address information Option.setcoortype ("Bd09ll");//The Locating knot returnedThe result is Baidu latitude and longitude, the default value of Gcj02 Option.setscanspan (5000);//Set the time interval for initiating a location request to 5000ms Option.disablecache (true);//disable cache location enabled    Option.setpoinumber (5); Returns the maximum number of POI option.setpoidistance (1000); Poi Query Distance Option.setpoiextrainfo (true);
		
	If you need details such as the phone and address of the POI mlocationclient.setlocoption (option);
		} @Override public void OnDestroy () {mlocationclient.stop ();//stop positioning mTv = null;
	Super.ondestroy (); }/** * Listener function, with update location, formatted as a string, output to the screen */public class Mylocationlistenner implements Bdlocationlistener {@Overri
			De//Receive location information public void Onreceivelocation (bdlocation) {if (position = = null) return;
			StringBuffer sb = new StringBuffer (256);
			Sb.append ("Time:");
			Sb.append (Location.gettime ());
			Sb.append ("\nreturn 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 ()); } else if (location.getloctype () = = bdlocation.typenetworklocation) {/** * format displays address information */sb.append ("\nadd
				R: ");
			Sb.append (Location.getaddrstr ());
			} sb.append ("\NSDK version:");
			Sb.append (Mlocationclient.getversion ());
			Sb.append ("\niscellchangeflag:");
			Sb.append (Location.iscellchangeflag ());
			Mtv.settext (Sb.tostring ());
		LOG.I (TAG, sb.tostring ()); }//Receive POI information function, I do not need poi, so I did not handle public void Onreceivepoi (Bdlocation poilocation) {if (poilocation = = null) {RE
			Turn }
		}
	}


}

Basic steps:

1, initialization: mlocationclient = new Locationclient (this);
2, set the listening function, that is, return the results after the function of how to deal with: Mlocationclient.registerlocationlistener (MyListener);

3, set the positioning parameters: Setlocationoption ();

4, start positioning: Mlocationclient.start ();

Note one thing:

1, after the start of positioning, if not call Mlocationclient.stop (), to stop the positioning, then the program will be relocated every few seconds, a waste of resources. In order to verify this, I am in the program, in the Onreceivelocation () function, using LOG.I (TAG, sb.tostring ()), recording the location information received each time and recorded in Logcat, the following is about half an hour later, That is the time I wrote this article, the "MSG" tag of the amount of information to 1777, visible program location how many times ....

Do not know how, just about one hours of positioning are unsuccessful, and return to errorcode:0, and then after a period of time, their success, and the forum said sometimes positioning quasi, sometimes positioning, MY GOD, this Baidu can not do ah. This time is good and bad, do very not practical ah.

Attach the meaning of the ErrorCode value, find a half-day or in the forum found, the use of the instructions, did not say, hey, China these help documents AH, no words.

Baidu Base Station positioning error return code

61:gps Locating results
62: Scan consolidation location based on failure. The positioning result is not valid at this time.
63: Network exception, the request was not successfully initiated to the server. The positioning result is not valid at this time.
65: The result of locating the cache.
66: Offline location results. The corresponding return result when called by Requestofflinelocaiton
67: Offline location failed. The corresponding return result when called by Requestofflinelocaiton
68: When a network connection fails, find the corresponding return results for local offline targeting
161: Network Targeting results
162~167: Service-side location failed.

on the source bar: http://download.csdn.net/detail/harvic880925/6781711(do not divide, close for sharing)

calculate the distance between two points by longitude and latitude

This formula I certainly do not know, Baidu, code formula What everything has, directly with OK, as to correctness, it should be right, here record

formula: (http://xxyyyboy.blog.163.com/blog/static/765832620110410457662/)

(km)

1.lat1 Lung1 represents the latitude and longitude of a point, Lat2 Lung2 represents the latitude and longitude of B point;

2.A=LAT1–LAT2 the difference between the latitude of two points and b=lung1-lung2 two points of longitude;

3.6378.137 is the radius of the Earth, the unit is kilometer;

The calculated result is measured in kilometers. Code

Someone (http://panyee.cnblogs.com/archive/2006/07/04/442771.html) from Google Map to extract the calculation code, have verified that is correct, anyway, I will not calculate, This code is also used in my software, as follows

Private Const Double Earth_radius = 6378.137;
private static Double rad (double D)
{
   return d * math.pi/180.0;
}

public static double Getdistance (double lat1, double lng1, double lat2, double lng2)
{
   double radLat1 = rad (LAT1);
   Double radLat2 = rad (LAT2);
   Double A = RADLAT1-RADLAT2;
   Double b = rad (lng1)-Rad (lng2);
   Double s = 2 * Math.asin (MATH.SQRT (Math.pow (Math.sin (A/2), 2) + 
    Math.Cos (RADLAT1) *math.cos (RADLAT2) *math.pow ( Math.sin (B/2), 2));
   s = S * earth_radius;
   s = Math.Round (S * 10000)/10000;
   return s;
}
Reference: "Android acquisition latitude and longitude, calculate distance, bearing angle" http://www.cnblogs.com/ouling/archive/2011/08/26/2154555.html


Reprint Please indicate the source, thank you, http://blog.csdn.net/harvic880925/article/details/17633311

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.