Android intermediate-level Baidu map SDK v3.5.0-Baidu map positioning [ultra-detailed graphic positioning Basics]

Source: Internet
Author: User

Android intermediate-level Baidu map SDK v3.5.0-Baidu map positioning [ultra-detailed graphic positioning Basics]
Detailed analysis and positioning coordinate-LatLng

The coordinates (longitude and latitude) are used most in positioning. First, we can figure out what coordinates are:

LatLngClass: basic geographic coordinate data structure.

Description Method Name
Constructor LatLng (double latitude, double longbench)

Field details

Description Field name Definition
Latitude Latitude Public final double latitude
Longitude Longpolling Public final double longpolling

Note: I often make mistakes in longitude and latitude. I don't know why. You should pay special attention when operating coordinates. The longitude and latitude data type isdoubleType.

Coordinate pick-up system

Coordinate pick-up system of Baidu

Every time you want to know the coordinates of a place or take a few example coordinates, you can use this. Click any place on the map to get the coordinates of the location (displayed in the box in the upper right corner). (focus on the content in the red box ):

Geographic range data structure-LatLngBounds

Geographic range data structure, confirmed by coordinate points in the southwest and Northeast China. Although it is not used much, it has a kinship with the coordinates, so we will not use it all.

GenerallyXXX.BuilderHope you can use it more, try notnewOf course, some classes do not have constructor methods; Summary of Nested classes:

Qualifier and type Class Description
Static class LatLngBounds. Builder Geographic range Constructor

Field Overview:

Qualifier and type Field Description
LatLng Northeast Northeast coordinates of the geographic range
LatLng Southwest The southwest coordinate of the geographic range

Method Overview:

Qualifier and type Method Description
Boolean Contains (LatLng point) Determines whether the specified geographic range contains a geographical location.
LatLng GetCenter () Obtain the central geographic coordinate of the geographic range

Method details:

Public boolean contains (LatLng point) determines whether the geographic range contains a geographic location parameter: point-the location to be determined returns: whether the geographic range contains a geographic location
Public LatLng getCenter () returns the central geographic coordinate of the geographic range.
Geographic range constructor-LatLngBounds. Builder

Constructor Overview:

Constructor Description
LatLngBounds. Builder () Constructor

Method Overview:

Qualifier and type Method Description
LatLngBounds Build () Create a geographic range object
LatLngBounds. Builder Include (LatLng point) Make the geographic range contain a geographic coordinate

Method details:

Public LatLngBounds build () creates a geographic range object. Return: The created geographic range object.
Public LatLngBounds. Builder include (LatLng point) allows the geographic range to contain a geographic coordinate parameter: point-geographic coordinate return: the constructor object

Example:

MBDMap. setOnMapLoadedCallback (new BaiduMap. onMapLoadedCallback () {@ Override public void onMapLoaded () {// coordinate range: LatLng northeast = new LatLng (121.445541, 31.192286); LatLng southwest = new LatLng (121.441624, 31.189922 ); latLngBounds llb = new LatLngBounds. builder (). include (northeast ). include (southwest ). build (); boolean isHas = llb. contains (new LatLng (121.443564, 31.190795); Log. v (this function is called when the map is loaded, but it still does not exist + isHas +, Northeast: + llb. northeast + Southwest China: + llb. southwest );}});

Simple Positioning

Createactivity_location.xml:


  
      
       
           
                
                 
       
      
     
        
       
  

WriteLocationDemoClass inherited fromBaseActivity:

/*** Activity base class */public class BaseActivity extends FragmentActivity {@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); // initialize the context information before using the SDK components, and pass in the ApplicationContext // note that this method must be implemented before the setContentView method. initialize (getApplicationContext ());}}
Public class LocationDemo extends BaseActivity implements View. onClickListener, RadioGroup. onCheckedChangeListener, BDLocationListener {private MapView mMapView; private BaiduMap mBDMap; // locate private Button requestLocBtn; // locate the layer display mode private MyLocationConfiguration. locationMode mCurrentMode; // User-Defined positioning icon private BitmapDescriptor mCurrentMarker; // radio button group private RadioGroup rg; // positioning related private LocationClient mLocClient; // whether to locate private boolean isFirstLoc = true for the first time; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_location); initView ();} private void initView () {// request to locate requestLocBtn = (Button) findViewById (R. id. location_btn); // positioning layer display mode mCurrentMode = MyLocationConfiguration. locationMode. NORMAL; requestLocBtn. setText (common); requestLocBtn. setOnClickListener (this); // radio button group rg = (RadioGroup) findViewById (R. id. location_rg); rg. setOnCheckedChangeListener (this); // map initialization mMapView = (MapView) findViewById (R. id. location_bdmap); mBDMap = mMapView. getMap (); // enable the positioning layer mBDMap. setMyLocationEnabled (true); // locate initialization mLocClient = new LocationClient (this); mLocClient. registerLocationListener (this); LocationClientOption option = new LocationClientOption (); option. setOpenGps (true); // enable GPS option. setCoorType (bd09ll); // sets the coordinate type option. setScanSpan (1000); // set the request interval mLocClient. setLocOption (option); // load the mLocClient configuration. start (); // start positioning} // click the event @ Override public void onClick (View v) {switch (mCurrentMode) {// normal state: no operations are performed on the map when location data is updated. case NORMAL: requestLocBtn. setText (follow); mCurrentMode = MyLocationConfiguration. locationMode. FOLLOWING; break; // In the COMPASS state, the orientation circle is displayed, and the position icon is kept in the map center. case COMPASS: requestLocBtn. setText (common); mCurrentMode = MyLocationConfiguration. locationMode. NORMAL; break; // follows the state and keeps the positioning icon in the map center case FOLLOWING: requestLocBtn. setText (Compass); mCurrentMode = MyLocationConfiguration. locationMode. COMPASS; break;} // sets the position layer display mode mBDMap. setMyLocationConfigeration (new MyLocationConfiguration (mCurrentMode, true, mCurrentMarker); // start locating mLocClient. start () ;}// single-choice event @ Override public void onCheckedChanged (RadioGroup group, int checkedId) {switch (checkedId) {case R. id. location_rb_defaulticon: // restores the default icon mCurrentMarker = null; break; case R. id. location_rb_customicon: // modify it to the custom Marker mCurrentMarker = BitmapDescriptorFactory. fromResource (R. mipmap. ic_launcher); break;} // sets the position layer display mode mBDMap. setMyLocationConfigeration (new MyLocationConfiguration (mCurrentMode, true, mCurrentMarker);} // location listener @ Override public void onReceiveLocation (BDLocation bdLocation) {// if the bdLocation is null or the position where new data is not processed after the mapView is destroyed if (bdLocation = null | mMapView = null) {return ;} // locate data MyLocationData data = new MyLocationData. builder () // precision (RADIUS ). accuracy (bdLocation. getRadius () // set the direction information obtained by the developer, Which is 0-360 clockwise. direction (100 ). latitude (bdLocation. getLatitude ()). longpolling (bdLocation. getlongpolling ()). build (); // sets the position data mBDMap. setMyLocationData (data); // whether it is the first time to locate if (isFirstLoc) {isFirstLoc = false; LatLng ll = new LatLng (bdLocation. getLatitude (), bdLocation. getlongpolling (); MapStatusUpdate msu = MapStatusUpdateFactory. newLatLng (ll); mBDMap. animateMapStatus (msu) ;}@ Override protected void onResume () {super. onResume (); mMapView. onResume () ;}@ Override protected void onPause () {super. onPause (); mMapView. onPause () ;}@ Override protected void onDestroy () {super. onDestroy (); // destroy the mLocClient when exiting. stop (); // close the positioning layer mBDMap. setMyLocationEnabled (false); mMapView. onDestroy (); mMapView = null ;}}

Run:

Configure the positioning layer display mode-MyLocationConfiguration

Constructor Overview:

Constructor Description
MyLocationConfiguration (MyLocationConfiguration. LocationMode mode, boolean enableDirection, BitmapDescriptor customMarker) Constructor

Constructor details:

Public MyLocationConfiguration (MyLocationConfiguration. locationMode mode, boolean enableDirection, BitmapDescriptor customMarker) constructor parameter: mode-specifies the layer display mode. The default value is LocationMode. NORMAL state enableDirection-whether to allow display direction information customMarker-set the custom positioning icon, which can be null updateTimeEscap-layer refresh frequency, in ms. If the default value is used, enter 0, default Value: 100 ms

Summary of Nested classes:

Qualifier and type Class Description
Static class MyLocationConfiguration. LocationMode Locate the layer Display Mode

Field Overview:

Qualifier and type Field Description
BitmapDescriptor CustomMarker Custom positioning icon
Boolean EnableDirection Whether to allow display of Direction information
MyLocationConfiguration. LocationMode LocationMode Locate the layer Display Mode
Locate the layer display method-MyLocationConfiguration. LocationMode

Enumeration constants summary:

Enumerated constant Description
COMPASS The orientation circle is displayed, and the positioning icon is kept in the map center.
FOLLOWING Keep the positioning icon in the Map Center
NORMAL Normal state: do not perform any operations on the map when updating the positioning data

Method Overview:

Qualifier and type Class Description
Static MyLocationConfiguration. LocationMode ValueOf (java. lang. String name) Returns an enumerated constant of the specified type.
Static MyLocationConfiguration. LocationMode [] Values () Returns an array containing constants in the declared order of constants of this enumeration type.

Method details:

Public static MyLocationConfiguration. LocationMode [] values () returns an array containing constants in the declared order of constants of this enumeration type. This method can be used for iteration constants, as shown below: for (MyLocationConfiguration. locationMode c: MyLocationConfiguration. locationMode. values () System. out. println (c); Return: returns an array containing constants in the declared order of constants of this enumeration type.
Public static MyLocationConfiguration. LocationMode valueOf (java. lang. String name) returns an enumerated constant of this type with the specified name. The string must exactly match the identifier used to declare an enumerated constant of this type. (Redundant space characters are not allowed .) Parameter: name-name of the enumerated constant to be returned. Return: return an enumeration constant with the specified name. Throw: If the enumerated type does not have a constant with the specified name, the system throws IllegalArgumentException. If the parameter is null, the system throws NullPointerException.
Locate data-MyLocationData

Summary of Nested classes:

Qualifier and type Class Description
Static class MyLocationData. Builder Locating data Builder

Field Overview:

Qualifier and type Field Description
Float Accuracy Positioning Accuracy
Float Direction GPS orientation
Double Latitude Baidu latitude coordinates
Double Longpolling Baidu longitude coordinates
Int SatellitesNum Number of satellites during GPS Positioning
Float Speed GPS Positioning speed
Locate the data Builder-MyLocationData. Builder

Constructor Overview:

Constructor Description
MyLocationData. Builder () Constructor

Method Overview:

Qualifier and type Method Description
MyLocationData. Builder Accuracy (float accuracy) Sets the precision of the positioning data, in meters.
MyLocationData Build () Build and generate positioning data objects
MyLocationData. Builder Direction (float direction) Set the direction of the positioning data
MyLocationData. Builder Latitude (double lat) Set the positioning data latitude
MyLocationData. Builder Longbench (double lng) Set the longitude of the positioning data
MyLocationData. Builder SatellitesNum (int num) Set the number of satellites for positioning data
MyLocationData. Builder Speed (float speed) Set the data locating speed

Method details:

Public MyLocationData. Builder latitude (double lat) sets the latitude parameter of the positioning data: lat-latitude return: the constructor object
Public MyLocationData. Builder longpolling (double lng) sets the longitude parameter of the positioning data: lng-longitude return: the constructor object
Public MyLocationData. Builder speed (float speed) sets the location data speed parameter: speed-return: the constructor object
Public MyLocationData. Builder direction (float direction) sets the direction information parameter of the positioning data: direction-direction return: the constructor object
Public MyLocationData. Builder accuracy (float accuracy) sets the precision information of the positioning data. Unit: meter parameter: accuracy-precision information; Unit: meter return: the constructor object
Public MyLocationData. Builder satellitesNum (int num) set the number of satellites for positioning data parameter: num-number of satellites return: the constructor object
Public MyLocationData build () build to generate location data object return: Generate Location Data Object
Destruction description

Let's look at our last method [onDestroy()]:

@ Override protected void onDestroy () {super. onDestroy (); // destroy the mLocClient when exiting. stop (); // close the positioning layer mBDMap. setMyLocationEnabled (false); mMapView. onDestroy (); mMapView = null ;}

Here, we must pay attention to the code sequence during writing, and secondly, we mustmMapView = null;Release the memory. Here is a knowledge point about memory recycling:

Ifstu=null, That isnew Student();This instance is not referenced, so it is regarded as spam in the heap memory. The virtual machine will not immediately recycle it, but it will certainly be recycled.

 

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.