Use Baidu Map API in Android app and add callout (i)

Source: Internet
Author: User
Tags ontap

Some information on the Internet such content is outdated, here is the latest content, assuming where is not correct, please spit groove ...

1) Download Baidu maps Mobile API (ANDROID) Development Kit
To use the Baidu Map API in Android, you need to refer to the Baidu Map API development package in project, which includes two files:

: Http://pan.baidu.com/s/1i31enrB

2) Application API Key

Package Name

Format: for example: B7:6c:cf:e2:47:50:9b:3e:34:f7:08:72:f3:ac:f1:be:55:d3:77:fb;com.majianjie.baidumap
Application Address: Http://lbsyun.baidu.com/apiconsole/key

3) Create a Androidproject folder structure such as the following:


4) Add a map control to the layout file (Res/layout/activity_main.xml)

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:layout_width=" fill_parent "    android:layout_height=" fill_parent "    android:o rientation= "vertical" >    <com.baidu.mapapi.map.mapview        android:id= "@+id/bmapview"        android: Layout_width= "Fill_parent"        android:layout_height= "fill_parent"        android:clickable= "true"/></ Linearlayout>

5) Create activity

Package Com.majianjie.baidumap;import Android.app.activity;import Android.graphics.bitmap;import Android.graphics.drawable.drawable;import Android.os.bundle;import Android.widget.toast;import Com.baidu.mapapi.bmapmanager;import Com.baidu.mapapi.mkgenerallistener;import com.baidu.mapapi.map.MKEvent; Import Com.baidu.mapapi.map.mkmapviewlistener;import Com.baidu.mapapi.map.mapcontroller;import Com.baidu.mapapi.map.mappoi;import Com.baidu.mapapi.map.mapview;import Com.baidu.mapapi.map.overlayitem;import Com.baidu.platform.comapi.basestruct.geopoint;import Com.example.baidumap.r;public class MainActivity extends Activity {private Toast mtoast;private bmapmanager mbmapmanager;public Mapview Mmapview = Null;//mapview is the map main control private Ma     Pcontroller Mmapcontroller = null;//with Mapcontroller complete map control mkmapviewlistener mmaplistener = null; Mkmapviewlistener for handling Map events callback//show traffic map @overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate ( savedinstancestate)/** * Before using the Map SDK, you need to initialize the Bmapmanager, this must be initialized at Setcontentview () First */mbmapmanager = new Bmapmanager (this);//The first parameter is API key, the second is the use of event snooping often to handle the usual network errors, Authorization validation error, etc., you can also not join this callback interface Mbmapmanager.init ("Ldth1svwr7kygaf0atqavwwu", new Mkgenerallistener () {// The callback function called when the authorization error @overridepublic void ongetpermissionstate (int ierror) {if (Ierror = = mkevent.error_permission_denied) { Showtoast ("API key error, please check!")            "); }}//Some network status error handling callback function @overridepublic void ongetnetworkstate (int ierror) {if (Ierror = = Mkevent.error_network_connect) { Toast.maketext (Getapplication (), "Your network is wrong!"            ", Toast.length_long). Show ();                }}); Setcontentview (r.layout.activity_main); Mmapview = (Mapview) Findviewbyid (R.id.bmapview);     Mmapcontroller = Mmapview.getcontroller ();                * Get Map Controller Mmapcontroller.enableclick (TRUE);         * Set whether the map responds to click events.      Mmapcontroller.setzoom (12);//* Set map zoom level Mmapview.setbuiltinzoomcontrols (TRUE); * Display built-in zoom control Mmapview.setsatellite (TRUE);//settings shown as satellite map://mmapview.setbuiltiNzoomcontrols (TRUE); /** * Use the following code where you want to join overlay, * For example, Activity's oncreate () *///Prepare to join overlay do          Uble MLAT1 = 39.904508;                 Double mLon1 = 119.53971899999999;          Constructs a GeoPoint with a given latitude and longitude, the unit is the Micro degree (degree * 1E6) GeoPoint p1 = new GeoPoint ((int) (MLAT1 * 1E6), (int) (MLon1 * 1E6));          Prepare overlay image data, repair drawable mark= getresources () according to the facts. Getdrawable (R.drawable.set);          Prepare overlay data with Overlayitem overlayitem item1 = new Overlayitem (P1, "Item1", "item1"); Use the Setmarker () method to set the overlay picture, assuming that you do not set the default setting when building Itemizedoverlay//Create Iteminizedoverlay Customitem          Izedoverlay itemoverlay = new Customitemizedoverlay (mark, Mmapview);          Add Iteminizedoverlay to Mapview mmapview.getoverlays (). Clear ();                     Mmapview.getoverlays (). Add (Itemoverlay);          Now that all preparations are ready, use the following methods to manage overlay. Join overlay, use AddItem when adding overlay in bulk (list<overlayitem>) Higher efficiency itemoverlay.additem (ITEM1);                  Mmapview.refresh ();        Mmapcontroller.setcenter (p1);//set P place as center point Mmapview.regmapviewlistener (Mbmapmanager, New Mkmapviewlistener () { * This interface method will be recalled when the map is moved @overridepublic void Onmapmovefinish () {showtoast ("The map has moved!") ");} * Map loading complete Callback This interface method @overridepublic void Onmaploadfinish () {showtoast ("Map loaded! ");} * This callback is triggered @overridepublic void Onmapanimationfinish () {}//when the map is finished (e.g., Animationto ()), and is called Mmapview.getcurrentmap ( ), this callback is triggered to be saved to the storage device @overridepublic void Ongetcurrentmap (Bitmap arg0) {}//* click on the map labeled Point callback this method @overridepublic void Onclickmappoi (Mappoi arg0) {if (arg0! = null) {showtoast (Arg0.strtext);}});} @Overrideprotected void Onresume () {//mapview life cycle is synchronized with activity, call Mapview.onpause () Mmapview.onresume () when activity hangs ; Super.onresume ();} The life cycle of the @Overrideprotected void OnPause () {//mapview is synchronized with the activity and calls Mapview.onpause () Mmapview.onpause () when the activity is suspended; Super.onpause ();} @Overrideprotected void OnDEstroy () {//mapview life cycle is synchronized with activity, call Mapview.destroy () Mmapview.destroy () when activity is destroyed;// Exit the app call Bmapmanager's Destroy () method if (Mbmapmanager! = null) {Mbmapmanager.destroy (); mbmapmanager = null;}     Super.ondestroy ();} * Show Toast message private void Showtoast (String msg) {if (mtoast = = null) {mtoast = toast.maketext (th          IS, MSG, toast.length_short);              }else{Mtoast.settext (msg);        Mtoast.setduration (Toast.length_short);      } mtoast.show (); } }

6) Configure join permissions in Androidmanifest.xml

<uses-permission android:name= "Android.permission.ACCESS_NETWORK_STATE"/>      <uses-permission android: Name= "Android.permission.ACCESS_FINE_LOCATION"/>      <uses-permission android:name= " Android.permission.INTERNET "/>      <uses-permission android:name=" android.permission.WRITE_EXTERNAL_ STORAGE "/>      <uses-permission android:name=" Android.permission.ACCESS_WIFI_STATE "/>      < Uses-permission android:name= "Android.permission.CHANGE_WIFI_STATE"/>      <uses-permission android:name= " Android.permission.READ_PHONE_STATE "/>  

7) Another file is defined by itself and inherits from:Itemizedoverlay (Baidu map, not Android own)

Overlay Brief Introduction
overlay are often translated as "layers" or "overlays". So what do you call a cover for a map? "Everything superimposed or overlaid onto the map is called a map overlay., such as callouts, vector graphic elements (including: Polylines and polygons, and circles), positioning icons, and so on. Overlays have their own geographic coordinates, and they move when you drag or zoom the map. "
in order to let us have a further understanding of the overlay, we will then use the following graphic to intuitively understand it. The red icons marked in the figure A, B,..., J is one of the overlay forms. Assuming you understand the concept of layers in Photoshop, this should not be difficult to understand. we can understand the relationship between a map, a layer, and a marker on a layer: those red tags are not part of the map, all of which are attached to the layer, and then the layer is masked on the map.

Baidu Map API provides several overlay
The Baidu Map API provides the following overlay (overlays):
1) Overlay: It is the abstract base class of all covering objects, all of which inherit the method of this class, realize the user's own definition layer display;
2) Mylocationoverlay: a responsibleoverlay showing the user's current location;
3) Itemizedoverlay: It includes a list of Overlayitem, equivalent tooverlay of a component bar, and by inheriting this class, a set of points of interest is displayed on the map;
4) Poioverlay:Local Search Layerto provide a location search service for a particular region, such as a search for "Parks" in Beijing, where the park is displayed on a map;
5) Routeoverlay:walking, driving navigation route layer, the route and key points of the walking and driving plan are shown on the map;
6) Transitoverlay:Bus transfer route layer, the route and transfer location of the public transport plan for a particular area are displayed on the map.


online some of the content is relatively early, Baidu Map API has abandoned the use of , here is the latest, specific:/HTTP developer.baidu.com/map/sdkandev-6.htm#. E7. AE.80.E4.BB.8B3

Package Com.majianjie.baidumap;import Android.graphics.drawable.drawable;import Com.baidu.mapapi.map.itemizedoverlay;import Com.baidu.mapapi.map.mapview;import Com.baidu.mapapi.map.OverlayItem ; Import Com.baidu.platform.comapi.basestruct.geopoint;public class Customitemizedoverlay extends Itemizedoverlay <OverlayItem> {      //Itemizedoverlay public customitemizedoverlay constructed with Mapview      (drawable Mark,mapview Mapview) {              super (Mark,mapview);      }      protected Boolean onTap (int index) {          //In this processing item click event          System.out.println ("Item OnTap:" +index);          return true;      }          public boolean OnTap (GeoPoint pt, Mapview mapview) {                  //In this process Mapview click events, when returning True                  Super.ontap (Pt,mapview);                  return false;          }  }          


Execution diagram:


Basically on these, Baidu map API content is very rich, then will join in succession, please continue to pay attention! Thank you! Assuming where is not correct, please spit the groove ...


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.