[Android] Baidu map development (2). Positioning city location and city POI search

Source: Internet
Author: User

[Android] Baidu map development (2). Positioning city location and city POI search
I. Knowledge about Baidu map city positioning and POI search

The previous article Baidu map development (1) describes how to apply for Baidu APIKey and solve the problem of displaying blank grids. this article mainly describes how to locate the city location, locate your location, and search for the Point of Interest (POI. so how to locate a location on Baidu map?
GeoPoint can be used to define the latitude and longitude. It stores the latitude and longitude values. You can use the getLastKnownLocation () method to obtain the Location object, and then locate the latitude and longitude and set it to the map center to display the current Location.
Geopoint (latitude value, longitude value) is in the unit of microness and needs to be multiplied by the power of 6 in 10. The core code is as follows:

// Obtain the current location String provider = LocationManager through the network. neTWORK_PROVIDER; Location location = locationManager. getLastKnownLocation (provider); Geopoint point = new Geopoint (int) (location. getLatitude * 1E6), (int) (location. getlong1_* 1E6); mMapController. setCenter (point );
In the same way, if you know the longitude and latitude of a city, you can set it as the current map center, which enables you to locate the city location. How can you get the longitude and latitude of a city?
Baidu Map API provides MKSearch. geocode (String address, String city) is used to search for the location of the specific address of a city. If only the city is searched, geocode (city, city) is used) you can. at the same time, the reverse address resolution function MKSearch. reverseGeocode (new GeoPoint (latitude, longlatitude) can be used to query specific addresses by entering the latitude and longitude.
The core code is as follows (the code is placed in different locations. For details, refer to the following example ):

// Initialize MKSearchmMKSearch = new MKSearch (); mMKSearch. init (mBMapManager, new MySearchListener (); // search for mMKSearch. geocode (city, city); // The internal class implements the MKSearchListener interface to implement the asynchronous search service public class MySearchListener implements MKSearchListener {@ Override public void onGetAddrResult (MKAddrInfo result, int iError) {// search by latitude and longitude and address... mMapController. setCenter (result. geoPt );}}
Baidu map API Search mainly implements a search service by initializing the MKSearch class and the MKSearchListener class of the result listening object. there are many methods in this class to implement different functions. The onGetAddrResult () method can search address information based on latitude and longitude, And the POI point search we need to implement is implemented through onGetPoiResult, you can use this method to search for bus routes.
The core code is as follows:
// The internal class implements the MKSearchListener interface to implement the asynchronous search service public class MySearchListener implements MKSearchListener {// latitude and longitude and address search result public void onGetAddrResult (MKAddrInfo result, int iError) {} // POI search results (range search, city POI search, and peripheral search) public void onGetPoiResult (MKPoiResult result, int type, int iError) {}// public void onGetDrivingRouteResult (MKDrivingRouteResult result, int iError) {}// public void onGetTransitRouteResult (MKTransitRouteResult, int iError) {}// walking Route Search result public void onGetWalkingRouteResult (MKWalkingRouteResult result, int iError) {}// get details public void onGetBusDetailResult (MKBusLineResult arg0, int arg1) {} public void merge (int arg0, int arg1) {} public void onget1_urlresult (mk1_urlresult arg0, int arg1, int arg2) {} public void Merge (MKSuggestionResult arg0, int arg1) {}}
In android, Baidu map can be used to add a map covering. What is a covering?
All contents that overlay or overwrite a map are collectively referred to as map covers. such as annotation, vector graphics elements (including: Line and polygon and circle), positioning icons, etc. the cover has its own geographic coordinates. When you drag or scale a map, they move accordingly.
The map API provides the following cover types:
1. the abstract base class of the Overlay cover. All the covers inherit this type of method to display custom layers.
2. MyLocationOverlay is an Overlay that displays the current user location.
3. ItemizedOverlay It is a base class of Overlay. It contains an OverlayItem list, which is equivalent to an Overlay of a group of items. by inheriting this class, a group of interest points are displayed on the map.
4. The PoiOverlay local search layer provides the location search service for a specific area. For example, search for "park" in Beijing and use this layer to display the park on the map.
5. RouteOverlay: Specifies the route and key points of the pedestrian driving plan on the map.
6. The TransitOverlay bus transfer line layer displays the route and Transfer Location of the bus trip plan in a specific area on the map.
Here we can use MyLocationOverlay to locate the current position to add a cover, or add a point of interest cover for search through PoiOverlay during the POI search process. The following describes the code and implementation.


Ii. Source Code Implementation :
First, set its activity_main.xml Layout

     
      
      
             
            
     
       
        
        
         
        
       
       
        
        
         
        
       
     
    
   
  
 

Then MainActivity. java source code

 

Public class MainActivity extends Activity {// BMapManager Object Management map, positioning, and search functions private BMapManager mBMapManager; private MapView mapView = null; // map master control private MapController mMapController = null; // map control MKMapViewListener mMapListener = null; // handle map Event Callback private MKSearch mMKSearch; // define search service class // search private EditText keyWordEditText; private EditText cityEditText; private Button queryButton; private static Strin GBuilder sb; private MyLocationOverlay myLocationOverlay; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState);/*** create an object BMapManager and initialize the object * assign an AK to init (APIKey, null) V2.4.1 in V2.3.1 * Note that the initialization operation is performed in setContentView () before */mBMapManager = new BMapManager (getApplication (); mBMapManager. init (null); setContentView (R. layout. activity_main); mapView = (Ma PView) findViewById (R. id. map_view); cityEditText = (EditText) findViewById (R. id. city_edittext); keyWordEditText = (EditText) findViewById (R. id. keyword_edittext); queryButton = (Button) findViewById (R. id. query_button); mMapController = mapView. getController (); // obtain the map controller mMapController. enableClick (true); // sets whether the map responds to the Click Event mMapController. setZoom (16); // The higher the map zoom level (3-19), the more detailed the mapView information. setBuiltInZoomContro Ls (true); // display the built-in zoom control/*** get the school longitude and latitude settings map center point */GeoPoint point = new GeoPoint (int) (39.96703*1E6 ), (int) (116.323772*1E6); mMapController. setCenter (point); mapView. regMapViewListener (mBMapManager, new MKMapViewListener () {/*** call back this interface method when map movement is complete */@ Override public void onMapMoveFinish () {// Toast. makeText (MainActivity. this, map movement, Toast. LENGTH_SHORT ). show ();}/*** call back this interface after the map is loaded */@ Override pub Lic void onMapLoadFinish () {Toast. makeText (MainActivity. this, map loading, Toast. LENGTH_SHORT ). show ();}/*** after the map completes the animation-carrying operation (for example, animationTo (), this callback is triggered */@ Override public void onMapAnimationFinish () {}/*** when mMapView is called. after getCurrentMap (), this callback will be triggered * can be saved to the storage device */@ Override public void onGetCurrentMap (Bitmap arg0) {}/*** click the marked point on the map to call back this method */@ Override public void onClickMapPoi (MapPoi arg0) {if (arg0! = Null) {Toast. makeText (MainActivity. this, arg0.strText, Toast. LENGTH_SHORT ). show () ;}});/*** initialize MKSearch to call the city and POI search */mMKSearch = new MKSearch (); mMKSearch. init (mBMapManager, new MySearchListener (); queryButton. setOnClickListener (new OnClickListener () {@ Override public void onClick (View v) {mMapController = mapView. getController (); mMapController. setZoom (10); sb = new StringBuilder (); // inside Clear capacity // enter the correct city keyword String city = cityEditText. getText (). toString (). trim (); String keyWord = keyWordEditText. getText (). toString (). trim (); if (city. isEmpty () {// The default city is Guiyang city = Guiyang;} // If the keyword is null, only search for city GEO to search geocode (adress, city) specific address and city if (keyWord. isEmpty () {mMKSearch. geocode (city, city);} else {// search city + keyword mMKSearch. setPoiPageCapacity (10); // Number of POI returned per page mMKSearch. poiSearchInCity (city, keyWord );}}});} @ Overrideprotected void onResume () {mapView. onResume (); if (mBMapManager! = Null) {mBMapManager. start () ;}super. onResume () ;}@ Overrideprotected void onDestroy () {mapView. destroy (); if (mBMapManager! = Null) {mBMapManager. destroy (); mBMapManager = null;} super. onDestroy () ;}@ Overrideprotected void onPause () {mapView. onPause (); if (mBMapManager! = Null) {mBMapManager. stop ();} super. onPause ();}/*** internal class implements the MKSearchListener interface, used to Implement Asynchronous Search Service */public class MySearchListener implements MKSearchListener {/*** search address information result based on latitude and longitude * at the same time, mMKSearch. geocode (city, city) returns to the function ** @ param result search result * @ param iError error number (0 indicates a correct return) * // @ Override public void onGetAddrResult (MKAddrInfo result, int iError) {if (result = null) {return;} StringBuffer sbcity = new StringBuffer (); sbcity. append (result. strAddr ). append (); // The position corresponding to the latitude and longitude mapView. getOverlays (). clear (); // clear all existing covers on the map mMapController. setCenter (result. geoPt); // set to map center // Add origin and refresh LocationData locationData = new LocationData (); locationData. latitude = result. geoPt. getLatitudeE6 (); locationData. longpolling = result. geoPt. getLongitudeE6 (); myLocationOverlay = new MyLocationOverlay (mapView); myLocationOverlay. setData (locationData); mapView. getOverlays (). add (myLocationOverlay); mapView. refresh (); // use AlertDialog to display the address information new AlertDialog. builder (MainActivity. this ). setTitle (display current city map ). setMessage (sbcity. toString ()). setPositiveButton (close, new DialogInterface. onClickListener () {public void onClick (DialogInterface dialog, int whichButton) {dialog. dismiss ();}}). create (). show ();}/*** POI search result (range search, city POI search, and peripheral search) ** @ param result search result * @ param type return result type, 21: poi list 7: City list) * @ param iError error code (0 indicates correct return) */@ Override public void onGetPoiResult (MKPoiResult result, int type, int iError) {if (result = null) {return;} // obtain POI and display mapView. getOverlays (). clear (); PoiOverlay poioverlay = new PoiOverlay (MainActivity. this, mapView); poioverlay. setData (result. getAllPoi (); // set the POI data mapView. getOverlays (). add (poioverlay); // add a point of interest to mapView on the map. refresh (); // set the coordinates of a search result to the center of the map if (result. getNumPois ()> 0) {MKPoiInfo poiInfo = result. getPoi (0); mMapController. setCenter (poiInfo.pt);} // Add StringBuffer to traverse the POI returned by the current page (only 10 are returned by default) sb. append (found in total ). append (result. getNumPois ()). append (POI); for (MKPoiInfo poiInfo: result. getAllPoi () {sb. append (name :). append (poiInfo. name ). append ();} // use AlertDialog to display the POI new AlertDialog found on the current page. builder (MainActivity. this ). setTitle (found POI information ). setMessage (sb. toString ()). setPositiveButton (close, new DialogInterface. onClickListener () {public void onClick (DialogInterface dialog, int whichButton) {dialog. dismiss ();}}). create (). show ();}/*** driving route search result ** @ param result search result * @ param iError error number (0 indicates a correct return) * // @ Override public void onGetDrivingRouteResult (MKDrivingRouteResult result, int iError) {}/*** bus transfer Route Search result ** @ param result search result * @ param iError error code (0 indicates a correct response) * // @ Override public void onGetTransitRouteResult (MKTransitRouteResult result, int iError) {}/*** walking Route Search result ** @ param result search result * @ param iError error code (0 indicates correct return) */@ Override public void onGetWalkingRouteResult (MKWalkingRouteResult result, int iError) {}@ Overridepublic void onGetBusDetailResult (MKBusLineResult arg0, int arg1) {// TODO Auto-generated method stub} @ Overridepublic void onGetPoiDetailSearchResult (int arg0, int arg1) {// TODO Auto-generated method stub} @ Overridepublic void onget1_urlresult (mk1_urlresult arg0, int arg1, int arg2) {// TODO Auto-generated method stub} @ Overridepublic void onGetSuggestionResult (MKSuggestionResult arg0, int arg1) {// TODO Auto-generated method stub }}}
Finally, set the AndroidManifest. xml file to apply for network permissions and set APIKey.
 
     
      
       
       
        
        
         
         
       
        
        
         
          
          
           
            
            
             
             
              
              
               
                
                 
                  
                 
                  
               
               
              
             
            
           
          
         
        
       
      
     
    
   
  
 
Shows the program running result:
When only the city name is entered, the map corresponding to the city is displayed, such as Guiyang.

POI points of interest are displayed when you enter the city + keyword, such as Peking University. Only 10 POI are displayed here.

Finally, I tested the county and showed it again, but I didn't do anything about city name error handling. For example, Shi Bing County, it shows that Baidu map's API is still very powerful. I hope I will continue to study it later!
Finally, I hope the article will be helpful to everyone. I just got in touch with android to develop Baidu map, and I still use V2.4.1. At the same time, I did not display the cover when searching for a city. I don't know why. if you have any errors or deficiencies, please try again! It is recommended that you take a look at the official documentation and the Demo provided by Baidu. The articles mainly refer to Baidu official documentation, Liu Feng's great god blog, and the first line of Android code.
 

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.