Android Baidu Map Custom bus route navigation _android

Source: Internet
Author: User
Tags drawtext gettext int size static class stub ontap

I. Description of the problem

Based on the Baidu map to retrieve the designated city designated public transport road map, the effect as shown in the figure

Second, the common component application class, the main creation and initialization of Bmapmanager

public class App extends application {static app Mdemoapp;//Baidu Mapapi Admin class public Bmapmanager Mbmapman = NULL;//Authorized key/
/Application Address: http://dev.baidu.com/wiki/static/imap/key/public String mstrkey = "Your Appkey"; Boolean m_bkeyright = true; Authorization key correct, verify through//common event monitoring, used to handle common network errors, authorization validation errors such as public static class Mygenerallistener implements Mkgenerallistener {@Overr
IDE public void ongetnetworkstate (int ierror) {log.d ("Mygenerallistener", "Ongetnetworkstate error is" + Ierror); Toast.maketext (App.mDemoApp.getApplicationContext), "Your network has gone wrong!"
", Toast.length_long). Show (); @Override public void ongetpermissionstate (int ierror) {log.d (' mygenerallistener ', ' ongetpermissionstate error is ' + iEr
ROR); if (Ierror = = mkevent.error_permission_denied) {//Authorization key error: Toast.maketext (App.mDemoApp.getApplicationContext (), " File input Correct authorization key!
", Toast.length_long). Show ();
App.mDemoApp.m_bKeyRight = false; @Override public void OnCreate () {log.v ("Bmapapidemoapp", "onCreate"); mdemoapp = this; Mbmapman = new BMapmanager (this);
Mbmapman.init (This.mstrkey, New Mygenerallistener ());
Mbmapman.getlocationmanager (). Setnotifyinternal (10, 5);
Super.oncreate (); @Override Call the Destroy () function of mapadpi before//app exits, avoiding the time consuming public void onterminate () {if (Mbmapman!= null) {mbmapman.de for duplicate initialization)
Stroy ();
Mbmapman = null;
} super.onterminate ();  }
}

Third, the route of the preparation of public transport layer (Customrouteoverlay) and icon identification (Customoverlayitem)

Customrouteoverlay Component Extensions Routeoverlay:

The main bus, walking and driving line layer, the bus, walk and drive the route and key points on the map, according to the starting point of the vehicle route and the end of the route of the search;

Customoverlayitem extension itemizedoverlay<overlayitem>:

A collection class of overlays that can be used to identify the coordinates of a map with the same attributes or attributes, Overlayitem This class object is an item object in Itemizedoverlay, which is the corresponding covering for each coordinate.

Customrouteoverlay Class Code:

public class Customrouteoverlay extends Routeoverlay {public activity ac; private mapview mapview; static arraylist<v
iew> overlayviews = new arraylist<view> (); Public Customrouteoverlay (Activity arg0, Mapview arg1) {super (arg0, arg1); ac = arg0; mapview = arg1;//TODO Auto-genera Ted Constructor stub} @Override protected Boolean onTap (int arg0) {//TODO auto-generated Method Stub//return Super.on
Tap (arg0);
return true; @Override public void SetData (Mkroute arg0) {//TODO auto-generated Method Stub super.setdata (arg0); Addhint (arg0);} p ublic void Addhints (Mkroute routes) {for (int i = 0; i < routes.getnumsteps (); i++) {drawable marker = Ac.getresource S (). Getdrawable (R.drawable.pop); Get the resources that need to be marked on the map marker.setbounds (0, 0, marker.getintrinsicwidth (), Marker.getintrinsicheight ()); Define position and bounds for maker overitemt Overitem = new Overitemt (Marker,ac, Routes.getstep (i). GetContent (), Routes.getstep (i).
GetPoint ()); Overlayitem over=new Overlayitem (routes. GET, NULL, NULL); Mapview.getoverlays (). Add (Overitem);
Add Itemizedoverlay instance to Mmapview} mapview.invalidate (); /** * Add instruction Route * @param routes */public void Addhint (Mkroute routes) {mapview.getoverlays (). Clear ()///MAPVIEW.R
Emoveallviewsinlayout ();
View Mpopview = Ac.getlayoutinflater (). Inflate (R.layout.popview, NULL); for (int i=0;i< overlayviews.size (); i++) {System.out.println ("Remove &" +i); Mapview.removeviewinlayout (
Overlayviews.get (i));
Overlayviews.remove (i);
} mapview.invalidate (); Add Itemizedoverlay for (int i = 0; i < routes.getnumsteps (); i++) {drawable marker = ac.getresources (). Getdrawable (R . Drawable.pop); Get the resources that need to be marked on the map marker.setbounds (0, 0, marker.getintrinsicwidth (), Marker.getintrinsicheight ());
Define position and boundary for maker Geopoint pt = Routes.getstep (i). GetPoint ();//=//Routes.get (i) getpoint ();
if (i!= 0 && i!= routes.getnumsteps ()-1) {Mpopview = Ac.getlayoutinflater (). Inflate (R.layout.popview, NULL); Mapview.addview (Mpopview, New Mapview.layoutparams (LayoUtparams.wrap_content, layoutparams.wrap_content, NULL, MapView.LayoutParams.TOP_LEFT));
Mpopview.setvisibility (View.gone); Mapview.updateviewlayout (Mpopview, New Mapview.layoutparams (Layoutparams.wrap_content, LayoutParams.WRAP_CONTENT,
PT, MapView.LayoutParams.BOTTOM_CENTER));
Mpopview.setvisibility (view.visible);
Button button = (button) Mpopview.findviewbyid (R.id.overlay_pop);
Button.settext (Routes.getstep (i). GetContent ());
Overlayviews.add (Mpopview);
Overlayviews.add (button); else {//modify starting point and end style-Custom Mpopview = Ac.getlayoutinflater (). Inflate (R.layout.popview, null); Mapview.addview (Mpopview, New Mapview.layoutparams (layoutparams.wrap_content, layoutparams.wrap_content, NULL, MapView.LayoutParams.TOP_LEFT
));
Mpopview.setvisibility (View.gone); Mapview.updateviewlayout (Mpopview, New Mapview.layoutparams (Layoutparams.wrap_content, LayoutParams.WRAP_CONTENT,
PT, MapView.LayoutParams.BOTTOM_CENTER));
Mpopview.setvisibility (view.visible); Button button = (Button) mpopview.findviewbyiD (R.id.overlay_pop);
Button.offsettopandbottom (100);
Button.settextcolor (Color.Blue);
Button.setbackgroundcolor (color.transparent);
Button.settext (Routes.getstep (i). GetContent ());
Overlayviews.add (Mpopview);
Overlayviews.add (button); }} class Overitemt extends itemizedoverlay<overlayitem> {private drawable marker; private context Mcontext; priv
Ate Geopoint p;
Private Overlayitem o;
Public overitemt (drawable marker, context context, String Title,geopoint p) {super (boundcenterbottom));
This.marker = marker;
This.mcontext = context;
THIS.P = p;
The three parameters of the construction Overlayitem are: item position, title text, text fragment o = new Overlayitem (p, title, title); Populate (); The CreateItem (int) method constructs the item. Once you have the data, call this method first, before calling other methods} public void UpdateOverlay () {populate ():} @Override public void Draw (Canvas Canvas, Mapview m Apview, Boolean Shadow) {//projection interface for transformation between screen pixel coordinates and latitude and longitude coordinates projection projection = mapview.getprojection (); for (int ind ex = Size ()-1; Index >= 0; index--) {//traverse mgeolist overlayitem oVerlayitem = GetItem (index);
Gets the item String title = Overlayitem.gettitle () of the given index;
Transforms the latitude to the screen pixel coordinates relative to the upper-left corner of the mapview point = Projection.topixels (Overlayitem.getpoint (), NULL);
You can add your drawing code here Paint Painttext = new Paint ();
Painttext.setcolor (Color.Blue);
Painttext.settextsize (15); Canvas.drawtext (title, point.x-30, Point.y, Painttext);
Draw text} super.draw (canvas, Mapview, shadow);
Adjusts a drawable boundary so that (0,0) is a pixel boundcenterbottom (marker) at the last line of the drawable bottom; @Override protected Overlayitem CreateItem (int i) {//TODO auto-generated method Stub return O.} @Override public int Size () {//TODO auto-generated method stub return 1;} @Override//process when clicked Event protected Boolean onTap (int i) {//update bubble position, and make
The display return is true; @Override public boolean OnTap (Geopoint arg0, Mapview arg1) {//TODO auto-generated Method Stub//popup Bubble//Itemizedo
VerlayDemo.mPopView.setVisibility (View.gone);
Return Super.ontap (arg0, arg1); }
}
}

Customoverlayitem Code:

public class Customoverlayitem extends itemizedoverlay<overlayitem> {//private list<overlayitem> geolist =
New Arraylist<overlayitem> ();
Private context Mcontext;
Private Overlayitem overlay;
Boolean showtext;
Private String title;
Private drawable marker; Public Customoverlayitem (drawable marker, context context, Geopoint p, String title,string Sinppet, Boolean showtext) {su
Per (Boundcenterbottom (marker));
This.mcontext = context;
The Geopoint is constructed with a given latitude and longitude, and the unit is a micro degree (degree * 1E6)//point = P;
This.showtext = Showtext;
This.title = title;
This.marker = marker;
overlay = new Overlayitem (p, title, Sinppet); Populate (); The CreateItem (int) method constructs the item. Once you have the data, call this method first @Override protected overlayitem createitem (int i) {return overlay} before calling another method} @Override public int size () {return 1;} @Override public void Draw (Canvas Canvas, Mapview Mapview, Boolean arg2) {//TODO auto-generated method
Stub super.draw (canvas, Mapview, arg2); Projection interface for the transformation between screen pixel coordinates and latitude and longitude coordinates projection ProJection = Mapview.getprojection ();
String title = Overlay.gettitle ();
Transforms the latitude to the screen pixel coordinates relative to the upper-left corner of the mapview point = Projection.topixels (Overlay.getpoint (), NULL);
You can add your drawing code here Paint Painttext = new Paint ();
Paint Paint = new Paint ();
Paint.setalpha (255);
Paint.setcolor (Color.dkgray);
Paint.setstrokewidth (5);
Painttext.setcolor (Color.Blue);
Painttext.settextsize (15);
Canvas.drawcircle (Point.x, POINT.Y, paint); Canvas.drawtext (title, point.x-30, point.y-50, Painttext);
Draws the text//adjusts a drawable boundary so that (0,0) is a pixel boundcenterbottom (marker) at the last line of the drawable bottom; @Override//processing when clicked Event protected Boolean onTap (int i) {if (Showtext) Toast.maketext (This.mcontext, Overlay.gettitle (), to Ast.
Length_short). Show ();
return true; }
}

Four, write the main program Buslinesearch, extend the mapactivity, realize the display of map information

public class Buslinesearch extends mapactivity {button mbtnsearch = null;//Search button Mapview Mmapview = null;//MAP View MKS Earch msearch = null;
Search module can also remove the map module using String mcityname = null independently;
Locationlistener Loc_listener;
App app = null;
Static Boolean flag = FALSE;
static thread thread; protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (
R.layout.buslinesearch);
App = (APP) this.getapplication (); if (App.mbmapman = = null) {App.mbmapman = new Bmapmanager (Getapplication ()); App.mBMapMan.init (App.mstrkey, New App.myge
Nerallistener ());
} app.mBMapMan.start ();
If you use the Map SDK, initialize the map activity super.initmapactivity (App.mbmapman);
Mmapview = (Mapview) Findviewbyid (R.id.bmapview);
Mmapview.setbuiltinzoomcontrols (TRUE);
The setting also displays overlay during the scaling animation, and the default is not to draw mmapview.setdrawoverlaywhenzooming (true);
Mmapview.setbuiltinzoomcontrols (TRUE); Initialize the search module, register event monitor Mapcontroller Mmapcontroller = Mmapview.getcontroller (); Get Mmapview control and can use it to control and drive panning and scaling Geopoint POint = new Geopoint ((int) (39.915 * 1E6), (int) (116.404 * 1E6)); A geopoint is constructed with a given latitude and longitude, and the unit is a micro degree (degree * 1E6) mmapcontroller.setcenter (point); Set the map center point Mmapcontroller.setzoom (15);
Set map zoom level Msearch = new Mksearch (); Msearch.init (App.mbmapman, New Mksearchlistener () {public void Ongetpoiresult (mkpoiresult res, int type, int error) {// The error number can refer to the definition in Mkevent if (Error!= 0 | | | res = = NULL) {Toast.maketext (buslinesearch.this, "Sorry, no results found", Toast.length_long). Show (
);
Return
}//System.out.println (res.tostring ());
Find the bus route poi node Mkpoiinfo curpoi = null;
int totalpoinum = Res.getnumpois ();
for (int idx = 0; idx < totalpoinum; idx++) {log.d ("busline", "the Busline is" + idx);
Curpoi = Res.getpoi (idx);
if (2 = Curpoi.epoitype) {break;}}
Msearch.buslinesearch (Mcityname, Curpoi.uid); public void Ongetdrivingrouteresult (mkdrivingrouteresult res, int error) {} public void Ongettransitrouteresult (Mktran Sitrouteresult res, int error) {Res.getplan (0). Getdistance ();} public void OngetwalKingrouteresult (mkwalkingrouteresult res, int error) {} public void Ongetaddrresult (mkaddrinfo res, int error) {} void Ongetbusdetailresult (mkbuslineresult result, int ierror) {if (ierror!= 0 | | | = NULL) {Toast.maketext
Nesearch.this, "Sorry, no results found", Toast.length_long. Show ();
Return
}//Result.getbusroute (). Get//Result.getbusroute (). Getstart (). toString ();
Customrouteoverlay routeoverlay = new Customrouteoverlay (buslinesearch.this, Mmapview);
Routeoverlay.setdata (Result.getbusroute ());
Mmapview.getoverlays (). Clear ();
System.out.println (Mmapview.getoverlays (). Size ());
Mmapview.getoverlays (). Add (Routeoverlay);
Mmapview.invalidate ();
Mmapview.getcontroller (). Animateto (Result.getbusroute (). Getstart ()); 
@Override public void Ongetsuggestionresult (mksuggestionresult res, int arg1) {//TODO auto-generated Method stub}});
Mlocationmanager.requestlocationupdates (listener); Register to locate event Loc_listener = new Locationlistener () {@Override public void onlocationchanged(Location Location) {if (location!= null) {String Strlog = String.Format ("Your current location: \ r \ n" Latitude:%f\r\n "+" Longitude:%f ", Location.getlongitude (), Lo
Cation.getlatitude ());
Flag = true;
drawable marker = getresources (). getdrawable (R.drawable.ic_launcher);
Final Geopoint p = new Geopoint ((int) (Location.getlatitude () * 1E6), (int) (Location.getlongitude () * 1E6));
Customoverlayitem item = new Customoverlayitem (marker, Buslinesearch.this, p, "My Position", "", false);
Mmapview.getoverlays (). Add (item);
Mmapview.getcontroller (). Animateto (P);
}
}
};
Set the response of the search button Mbtnsearch = (button) Findviewbyid (R.id.search);
Onclicklistener Clicklistener = new Onclicklistener () {public void OnClick (View v) {searchbuttonprocess (v);}};
Mbtnsearch.setonclicklistener (Clicklistener); } void Searchbuttonprocess (View v) {if (Mbtnsearch.equals (v)) {mmapview.getoverlays (). Clear (); Mmapview.getoverlays ()
. RemoveAll (Mmapview.getoverlays ());
Mmapview.invalidate ();
EditText editcity = (edittext) Findviewbyid (r.id.city); EdittExt Editsearchkey = (edittext) Findviewbyid (R.id.searchkey);
Mcityname = Editcity.gettext (). toString ();
Msearch.poisearchincity (Mcityname, Editsearchkey.gettext (). toString ()); }} @Override protected void OnPause () {if (null = app) app = (APP) this.getapplication (); App.mBMapMan.getLocationManag
ER (). removeupdates (Loc_listener);
App.mBMapMan.stop ();
Super.onpause (); @Override protected void Onresume () {if (null = app) app = (APP) this.getapplication (); App.mBMapMan.start (); Super.on
Resume (); App.mBMapMan.getLocationManager (). Requestlocationupdates (Loc_listener);//Locate} @Override protected Boolean Isroutedisplayed () {//Todo auto-generated method stub return false;} @Override protected void OnDestroy () {//Todo Aut
o-generated method Stub Super.ondestroy (); }
}

The above code content is for Android Baidu map custom bus route navigation related knowledge, hope to be helpful to everybody.

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.