Use Baidu map API to locate your location in Android applications (2)

Source: Internet
Author: User

 

The Baidu map SDK provides developers with the following types of map covers:

  • MyLocationOverlay: The layer used to display the user's current position (custom position icons are supported );

  • PoiOverlay: A layer used to display the search results of interest points;

  • Roadmap layer (RouteOverlay): Bus, walking and driving line layer, display the routes and key points of bus, walking, and driving routes on the map (you can customize the start and end icons );

  • Bus Transfer Layer (TransitOverlay): Bus Transfer Line layer, display the route and transfer location of a bus trip plan in a specific region on the map (you can customize the start and end icons );

  • Custom layer (ItemizedOverlay): allows you to draw one or more points of interest on a map, and supports custom icons (supports dynamic update of Item positions and icons );

  • PopupOverlay: a pop-up window is displayed on the map;

  • GraphicsOverlay: A layer used to draw geometric figures such as points, line segments, arcs, circles, rectangles, and polygon;

  • TextOverlay: A layer used to draw text.

  • GroundOverlay: used to display the layers that the user passes in the image.

  • Panorama layer (PanoramaOverlay): points of interest in a panorama. You can customize the icon style.

    Note: In addition to the pop-up window layer, multiple instances are available for each layer. A Panorama layer is a special layer Used for a panorama.

    MapView uses a List to manage the covering. You can add or delete a covering to or from a map by adding or removing an instance of the above class or its base class to MapView. getOverlays. After Updating the map cover, you must call MapView. refresh () to make the update take effect.

     

     

    Positioning Principle

    To use the Baidu Android positioning SDK, you must register the GPS and network permission. The positioning SDK uses GPS, base station, and Wi-Fi signals for positioning. When an application initiates a positioning request to the positioning SDK, the positioning SDK will be based on the positioning factors (GPS, base station, Wi-Fi signal) of the application) to generate the corresponding positioning basis.
    Users can set the positioning basis to meet their own needs:
    If the user sets GPS priority, GPS is used for positioning first. If GPS positioning is not enabled or there is no available location information, and the network connection is normal, the positioning SDK returns the optimal result of Network Positioning (that is, Wi-Fi and base station. To make the obtained Network Positioning results more accurate, turn on the Wi-Fi switch of your mobile phone.

     

    The following two classes are used: MyLocationOverlay and PopupOverlay.

     

    1. Import the warehouse receiving File

    Before using Baidu to locate SDKv4.0, We need to download the latest library file: Click to download the relevant library file and copy the liblocSDK4.so file to the libs/armeabi directory. Copy the locSDK4.0.jar file to the libs directory of the project.

    The directory structure is as follows:

    Library File: http:/Repository? Http://www.bkjia.com/kf/ware/vc/ "target =" _ blank "class =" keylink "> volumes/iAuILK8vtbOxLz + o6zSu7j2sNm2yLXYzby/2Lz + volumes + CjxwcmUgY2xhc3M9" brush: java; ">
    Then the main Activity

     

     

    Package com. majianjie. baidumap; import android. app. activity; import android. graphics. bitmap; import android. graphics. drawable. drawable; import android. OS. bundle; import android. view. layoutInflater; import android. view. menu; import android. view. menuItem; import android. view. view; import android. view. view. measureSpec; import android. widget. button; import android. widget. textView; import android. widget. toast; impor T com. baidu. location. BDLocation; import com. baidu. location. BDLocationListener; import com. baidu. location. locationClient; import com. baidu. location. locationClientOption; import com. baidu. mapapi. BMapManager; import com. baidu. mapapi. MKGeneralListener; import com. baidu. mapapi. map. locationData; import com. baidu. mapapi. map. MKEvent; import com. baidu. mapapi. map. MKMapViewListener; import com. baidu. mapapi. map. mapCon Troller; import com. baidu. mapapi. map. mapPoi; import com. baidu. mapapi. map. mapView; import com. baidu. mapapi. map. myLocationOverlay; import com. baidu. mapapi. map. popupClickListener; import com. baidu. mapapi. map. popupOverlay; import com. baidu. platform. comapi. basestruct. geoPoint; import com. example. baidumap. r; public class MainActivity extends Activity {// declare the control private Button request; private Toast mToast = null; priva Te BMapManager mBMapManager = null; private MapView mMapView = null; // MapView is the map master control private MapController mMapController = null; // map control private LocationClient mLocClient using MapController; public LocationData mLocData = null; private LocationOverlay myLocationOverlay = null; // positioning layer private boolean isRequest = false; // whether to manually trigger the request to locate private boolean isFirstLoc = true; // whether to locate private PopupOverlay mPopupOverlay = for the first time Null; // the pop-up bubble layer. When browsing nodes, use private View viewCache = null; public BDLocation location = new BDLocation (); @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); // ** before using the map sdk, You need to initialize BMapManager. this parameter must be initialized before setContentView (). mBMapManager = new BMapManager (this ); // The first parameter is the API key, and the second parameter is the common event listener, which is used to handle common network errors and authorization verification errors. You can also leave this callback interface mBMapManager empty. init (LDtH1sVwr7kygaF0aTqaVwWU, new MKG EneralListener () {// callback function called when an authorization error occurs @ Overridepublic void onGetPermissionState (int iError) {if (iError = MKEvent. ERROR_PERMISSION_DENIED) {showToast (api key error, please check !);} // Some network status error handling callback functions @ Overridepublic void onGetNetworkState (int iError) {if (iError = MKEvent. ERROR_NETWORK_CONNECT) {Toast. makeText (getApplication (), your network has an error !, Toast. LENGTH_LONG ). show () ;}}); // initialize init (); // click Event click ();} // * display the Toast message private void showToast (String msg) {if (mToast = null) {mToast = Toast. makeText (this, msg, Toast. LENGTH_SHORT);} else {mToast. setText (msg); mToast. setDuration (Toast. LENGTH_SHORT);} mToast. show ();} private void click () {request. setOnClickListener (new View. onClickListener () {@ Overridepublic void onClick (View arg0) {requestLocation () ;}}) ;}@ Overrideprotected void onResume () {// synchronize the life cycle of MapView with Activity, when the activity is suspended, MapView must be called. onPause () mMapView. onResume (); mBMapManager. start (); // restart super. onResume () ;}@ Overrideprotected void onPause () {// synchronize the life cycle of MapView with the Activity. MapView must be called when the activity is suspended. onPause () mMapView. onPause (); super. onPause ();} private void init () {// use a custom title. Pay attention to the sequence setContentView (R. layout. activity_main); // activity layout // here is the custom titlebtn. xml // find their mMapView = (com. baidu. mapapi. map. mapView) findViewById (R. id. bmapView); mMapController = mMapView. getController (); // obtain the map controller mMapController. enableClick (true); // sets whether the map responds to the Click Event request = (Button) findViewById (R. id. request); viewCache = LayoutInflater. from (this ). inflate (R. layout. pop_layout, null); mPopupOverlay = new PopupOverlay (mMapView, new PopupClickListener () {// * click the method of layer callback in the pop-up window @ Overridepublic void onClickedPopup (int arg0) {// hide the pop-up window layer mPopupOverlay. hidePop () ;}}); mMapController. enableClick (true); // * sets whether the map responds to the click event. mMapController. setZoom (12); // * sets the map zoom level (mMapView. setBuiltInZoomControls (true); // * display the built-in zoom control mMapView. setTraffic (true); mLocData = new LocationData (); mLocClient = new LocationClient (getApplicationContext (); // * locate the SDK's core class // instantiate the positioning service, the LocationClient class must declare mLocClient in the main thread. registerLocationListener (new BDLocationListenerImpl (); // register the location listening interface/*** set the location parameter */LocationClientOption option = new LocationClientOption (); option. setOpenGps (true); // enable gpsoption. setAddrType (all); // The returned positioning result contains the address information option. setCoorType (bd09ll); // The returned positioning result is Baidu longitude and latitude. The default value is gcj02option. setScanSpan (5000); // you can specify a time interval of msoption to initiate a request. disableCache (false); // disable cache locating option. setPoiNumber (5); // maximum number of returned POI options. setPoiDistance (1000); // poi query distance option. setPoiExtraInfo (true); // whether the POI phone number, address, and other details are required. mLocClient. setLocOption (option); mLocClient. start (); // call this method to start locating myLocationOverlay = new LocationOverlay (mMapView); // locate layer initialization // set the Locating data to myLocationOverlay In the locating layer. setMarker (getResources (). getDrawable (R. drawable. set); // Add the positioning layer mMapView. getOverlays (). add (myLocationOverlay); myLocationOverlay. enableCompass (); // update the layer data to take effect after refreshing mMapView. refresh ();/* // Overlay double mLat1 = 39.910159 to be added; double mLon1 = 119.544697; // construct a GeoPoint with a given latitude and longitude, in the unit of (degree * 1E6) geoPoint p1 = new GeoPoint (int) (mLat1 * 1E6), (int) (mLon1 * 1E6); // prepare overlay image data, fix Drawable mark = getResources () based on actual conditions (). getDrawable (R. drawable. set); // use OverlayItem to prepare Overlay data OverlayItem item1 = new OverlayItem (p1, item1, item1); // use setMarker () to set overlay images, if this parameter is not set, use the default setting when constructing ItemizedOverlay. // create IteminizedOverlay CustomItemizedOverlay itemOverlay = new layout (mark, mMapView). // Add IteminizedOverlay to mMapView in MapView. getOverlays (). clear (); mMapView. getOverlays (). add (itemOverlay); // now all preparations are ready. Use the following method to manage overlay. // Add overlay. addItem (List
       
        
    ) More efficient itemOverlay. addItem (item1); // Delete overlay. // itemOverlay. removeItem (itemOverlay. getItem (0); // mMapView. refresh (); // clear overlay // itemOverlay. removeAll (); // mMapView. refresh (); mMapView. refresh (); * // mMapController. setCenter (p1); mMapView. regMapViewListener (mBMapManager, new MKMapViewListener () {// * this interface method is called back when map movement is completed @ Overridepublic void onMapMoveFinish () {showToast (MAP movement completed !);} // * Call back this interface method after the map is loaded @ Overridepublic void onMapLoadFinish () {showToast (the map is loaded !);} // * After the map completes the animation operation (for example, animationTo (), this callback is triggered @ Overridepublic void onMapAnimationFinish () {}// when mMapView is called. after getCurrentMap (), this callback is triggered and can be saved to the storage device @ Overridepublic void onGetCurrentMap (Bitmap arg0) {} // * click the marked point to callback this method @ Overridepublic void onClickMapPoi (MapPoi arg0) {if (arg0! = Null) {showToast (arg0.strText) ;}}) ;}@ Overridepublic boolean onCreateOptionsMenu (Menu menu) {super. onCreateOptionsMenu (menu); CreateMenu (menu); return true;} private void CreateMenu (Menu menu) {MenuItem mnu1 = menu. add (0, 0, 0, display satellite map); {mnu1.setAlphabeticShortcut ('A'); // set the shortcut key // mnu1.serIcon (R. drawable. icon); // set the image} MenuItem mnu2 = menu. add (, 1, display the street map); {mnu2.setAlphabeticShortcut ('B'); // set the shortcut key // mnu1.serIcon (R. drawable. icon); // set the image} MenuItem mnu3 = menu. add (, 2, 3D map); {mnu3.setAlphabeticShortcut ('C'); // set the shortcut key // mnu1.serIcon (R. drawable. icon); // set image }}@ Override public boolean onOptionsItemSelected (MenuItem item) {if (item. getItemId () = 0) {mMapView. setSatellite (true); // set to display as a satellite map: mMapView. setTraffic (false);} else if (item. getItemId () = 1) {mMapView. setTraffic (true); // display the mMapView of the street map. setSatellite (false );} Else if (item. getItemId () = 2) {// mMapView. se} return true;} public class BDLocationListenerImpl implements BDLocationListener {// * receives the location result returned asynchronously. The parameter is the BDLocation parameter @ Override public void onReceiveLocation (BDLocation location) {if (location = null) {return;}/* StringBuffer sb = new StringBuffer (256); sb. append (time:); sb. append (location. getTime (); sb. append (error code:); sb. append (locatio N. getLocType (); sb. append (latitude:); sb. append (location. getLatitude (); sb. append (lontitude:); sb. append (location. getlongpolling (); sb. append (radius:); sb. append (location. getRadius (); if (location. getLocType () = BDLocation. typeGpsLocation) {sb. append (speed:); sb. append (location. getSpeed (); sb. append (satellite:); sb. append (location. getSatelliteNumber ();} else if (location. getLocType () = BDLocation. typeNetWorkLocation) {sb. append (addr:); sb. append (location. getAddrStr ();} */MainActivity. this. location = location; mLocData. latitude = location. getLatitude (); mLocData. longpolling = location. getlongpolling (); // If the positioning precision circle is not displayed, assign the value of accuracy to 0 to mLocData. accuracy = location. getRadius (); mLocData. direction = location. getDerect (); // set the positioning data to myLocationOverlay In the positioning layer. setData (mLocData); // update a Layer MMapView takes effect after data is refreshed. refresh (); if (isFirstLoc | isRequest) {// animation the given position point to the map center mMapController. animateTo (new GeoPoint (int) (location. getLatitude () * 1e6), (int) (location. getlongpolling () * 1e6); showPopupOverlay (location); // when loading, isRequest = false;} isFirstLoc = false;} // receives the POI query result returned asynchronously, the parameter is a BDLocation parameter @ Override public void onReceivePoi (BDLocation poiLocation) {}} private void reques TLocation () {isRequest = true; if (mLocClient! = Null & mLocClient. isStarted () {showToast (locating ......); mLocClient. requestLocation () ;}}// inherit from MyLocationOverlay override dispatchTap method private class LocationOverlay extends MyLocationOverlay {public LocationOverlay (MapView arg0) {super (arg0 );} // * process click events on the "My location" coordinate. @ Override protected boolean dispatchTap () {// click my location to display PopupOverlay showPopupOverlay (location); return super. dispatchTap () ;}@ Overridepublic void setMarker (Drawable arg0) {super. setMarker (arg0) ;}@overrideprotected void onDestroy () {// The Life Cycle of MapView is synchronized with the Activity. When the activity is destroyed, MapView must be called. destroy () mMapView. destroy (); // exit the application and call the destroy () method of BMapManager if (mBMapManager! = Null) {mBMapManager. destroy (); mBMapManager = null;} // if (mLocClient! = Null) {mLocClient. stop ();} super. onDestroy ();} // * display the pop-up window layer PopupOverlay private void showPopupOverlay (BDLocation location) {TextView popText = (TextView) viewCache. findViewById (R. id. location_tips); popText. setText ([my location] + location. getAddrStr (); mPopupOverlay. showPopup (getBitmapFromView (popText), new GeoPoint (int) (location. getLatitude () * 1e6), (int) (location. getlongpolling () * 1e6), 15);} // * convert the View to the Bitmap public static Bitmap getBitmapFromView (View view) {view. measure (MeasureSpec. makeMeasureSpec (0, MeasureSpec. UNSPECIFIED), MeasureSpec. makeMeasureSpec (0, MeasureSpec. UNSPECIFIED); view. layout (0, 0, view. getMeasuredWidth (), view. getMeasuredHeight (); view. buildDrawingCache (); Bitmap bitmap = view. getDrawingCache (); return bitmap ;}}
       

    Note: Here I have commented out the code for adding a marker last time because I cannot add a tag to the current position when both of them are done at the same time... This problem will be solved later.

    The following layout file is the layout of the pop-up box, a very simple file: pop_layout.xml

       
       
        
                  />         
        
       

     

     

     

     

    • The LocationClient locates the core class of the SDK. The LocationClient class must be declared in the main thread. Parameters of the Context type are required. We recommend that you use getApplicationConext to obtain the Context of the entire process when the context is required. We call the registerLocationListener (BDLocationListener) method to register the location listening interface. There are two methods in BDLocationListener, oncancelocation () (receives the location result returned asynchronously) and onReceivePoi () (receives the result of the POI query returned asynchronously. POI is short for "Point of Interest" and can be translated into "information points ", each POI contains four types of information: name, category, longitude, latitude, nearby hotels, restaurants, and shops. We can call it "navigation map information", and navigation map data is the cornerstone of the entire navigation industry). Here we only need to rewrite onReceiveLocation to encapsulate the Positioning Result of the positioning SDK in BDLocation, obtain it in the onReceive method of BDLocationListener. Users of this type can obtain the error code, coordinates of the location, precision radius, address, and other information. For the error code obtained by the getLocType () method
      1. 61: GPS Positioning Result 62: Scan integration positioning basis failed. The positioning result is invalid. 63: failed to initiate a request to the server due to a network exception. The positioning result is invalid. 65: locate the cache results. 66: offline location result. Result 67 returned when calling requestOfflineLocaiton: offline location failed. Returned results for calling requestOfflineLocaiton 68: when the network connection fails, 161 is returned when the local offline location is located: 162 ~ 167: An error occurred while locating the server.
        • LocationClientOption is used to set the Positioning Method of the positioning SDK, for example, to enable GPS, to set whether the address information is required, and to set the interval between initiating a positioning request, after setting the parameters, call the setLocOption method LocationOverlay MyLocationOverlay subclass of the LocationClient, override the dispatchTap () method, display the pop-up window layer PopupOverlay, and call mMapView. getOverlays (). add (myLocationOverlay) adds my position layer to the PopupOverlay pop-up layer in the map. This class is still relatively simple. There are only three methods in it: hidePop () (hide the pop-up layer) showPopup (Bitmap pop, GeoPoint point, int yOffset) (display pop-up layer) and showPopup to display multiple images overload method, due to the showPopup Method Only Bitmap objects are accepted. Therefore, we must convert the View object of the pop-up layer to a Bitmap object. We call the getBitmapFromView method to achieve this conversion: BDLocationListener interface oncancelocation (BDLocation location) I will also explain the method in detail. We will find that the onReceiveLocation method will be executed repeatedly. The execution interval is related to the value set by the setScanSpan () method of the LocationClientOption class. We set it to 5000 milliseconds, the onReceiveLocation method is executed every 5 seconds. Note that when the value we set is greater than 1000 (MS), the location SDK uses the regular location mode internally. After requestLocation () is called, the SDK is located at a specified time. If the location of the SDK is not changed based on the location, no network request is initiated and the last location is returned. If the location is changed, the network request is located, get the new positioning result. If you only need to locate the location once, this setting is smaller than 1000, or you do not need to set it. When you locate the location regularly, you can call requestLocation once, And the location result 4 will be monitored regularly. before running the program, we must also. xml for configuration and permission Declaration

           

              
                       
                        
                         
                          
                           
                         
                          
                           
                            
                            
                           
                          
                         
                        
                       
                      
                     
                    
                   

          It is also important to add the following content to AndroidManifest. xml.

           

           

          Android: name = com. baidu. location. f
          Android: enabled = true
          Android: process =: remote>


          Android: name = com. baidu. lbsapi. API_KEY
          Android: value = 6KOX4mXHeBRzgriV6OP1T2Hw
          />

          Here's the meta-data problem: If you say this on the internet, remember it ....

          The sdk requires a key value, but the sdk value does not have to be assigned directly in mapManager.
          Therefore, you need to register in the registry form.

          Run illustration:

          Apk: http://pan.baidu.com/s/1hqqWSuw

          Part of the content is taken from the official Baidu document. Part from blog: http://blog.csdn.net/xiaanming/article/details/11380619

          Locating your own location is basically about this content, and problems will be added later .. That's it today .. I went to dinner ..

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.