Baidu Map API detailed bus navigation

Source: Internet
Author: User
Tags polyline

Original address: http://blog.csdn.net/sup_heaven/article/details/8461593

Just as a memo!!!

A debugging Baidu map multi-marker event monitoring problem, do not know how to solve, later read the original author jz1108 only know to use closures. Think the original author jz1108 about Baidu map of the article written good, so reproduced to CSDN, in order to respect the original author jz1108, hereby explain.

Before we introduced the driving navigation, today said the bus navigation.

What is bus navigation

The bus navigation function is to tell the user from A to B bus travel plan, rather than a specific bus line information, which requires the attention of the general developers.

Bus navigation function through class Transitroute to achieve, here need to say why not busroute, but transitroute. Baidu provides public transport navigation, public transport not only involves buses, there may also be subways, ferries and even later aircraft trains, so here is a description of the transit used in transit.

A simple example

Let's start with a simple example:

var transit = new Bmap.transitroute (' Beijing ', {    renderoptions: {        map:map,        Panel: ' Panel '    }}); Transit.search (' Xidan ', ' Summer Palace ');

The code sets the ID of the rendered map instance and the sidebar panel container through Renderoptions, where map is already instantiated and the panel is the ID of the prepared DIV element. We will see the following results:

A scenario is shown on the map, and a description of all the scenarios is listed in the panel, and a different solution map is displayed.

In addition to using string types, you can provide coordinates for querying, which results in a more accurate result. For example, from "McDonald's" to "KFC" such a route query will not get results, because the API does not know from which McDonald's to which KFC. The following example uses coordinates to search.

Transit.search (New Bmap.point (116.315157,39.987946),                new Bmap.point (116.371499,39.880394));

The following is the result of a query using coordinates as a parameter:

Note that because coordinates are provided, there is no specific location description for the start and end points.

Similar to driving navigation, the start and end points can also be localresultpoi types, and we use the coordinates above to query, but are encapsulated in a Localresultpoi type:

Transit.search ({title: ' I am here ', point:new bmap.point (116.315157,39.987946)},                {title: ' You Here ', Point:new bmap.point ( 116.371499,39.880394)});

This allows the API to display a description of the start and end points when the results are displayed.

Custom Overlay Display

If you are not satisfied with the color and callout style of the default line provided by the API, you can also choose to create it yourself by using the data interface. Note that when you create the overlay yourself, clicking on a scenario in the list will not update the map area because the elements of the map area are created by the developer themselves. Before using the data interface, a structure diagram is used to understand the various components of a complete transit plan to facilitate understanding:

A bus plan that does not require a transfer is made up of: The starting point, the starting point, the pedestrian line from the station, the bus line from the station to the next station, and the walking line to the end of the station. Of course, it is possible that the starting point and the station are coincident, or the end point and the drop-off station is coincident, the length of the Walking line is 0 (the starting point or the end point itself is the bus station when). If there is a transfer, there is also a walking route (as shown in the second scenario) for each transfer from the drop-off station to the upper station.

So no matter what the bus plan is, the representation on the data is consistent:

    • Direct plan: 2 walking lines + 1 bus lines
    • Transfer plan: 3 walking lines + 2 bus lines
    • Transfer two times plan: 4 Walking lines + 3 bus lines

And so on

The API uses Transitrouteresult to describe the results of bus navigation and describes a public transit scheme through Transitrouteplan. So how to get bus navigation results and specific information about the program? Take a look at the following example:

var transit = new Bmap.transitroute (' Beijing ', {onsearchcomplete:function (result) {if (transit.getstatus () = = BMap            _status_success) {//Get start and end information from the result object var start = Result.getstart ();            var end = Result.getend ();            Addstart (Start.point, start.title);            AddEnd (End.point, end.title);            Get the first solution directly var plan = Result.getplan (0); Traverse all walking lines for (var i = 0; i < plan.getnumroutes (); i++) {if (Plan.getroute (i). Getdistance (                False) > 0) {//judge only a walking line greater than 0 will draw Addwalkroute (Plan.getroute (i). GetPath ());            }}//Traverse all bus lines var alllinepath = [];                for (i = 0; i < plan.getnumlines (); i++) {Alllinepath = Alllinepath.concat (Plan.getline (i). GetPath ());            AddLine (Plan.getline (i). GetPath ()); }//finally set the map vision according to the point of the bus line Map.setviewport (AllliNepath); }}); Transit.search (' Peking University ', ' Beijing Jiaotong University ');//Add Start Overlay function Addstart (point, title) {Map.addoverlay (new Bmap.marker (POI NT, {title:title, icon:new bmap.icon (' http://images.cnblogs.com/cnblogs_com/jz1108/329471/o_blue.png ', NE W bmap.size ($), {anchor:new bmap.size (4, 36)})}); Add end-of-cover function addEnd (point, title) {Map.addoverlay (new Bmap.marker (points, {title:title, icon:new  Bmap.icon (' Http://images.cnblogs.com/cnblogs_com/jz1108/329471/o_red.png ', new bmap.size (+), {anchor:new Bmap.size (4, 36)}));}) Add route function Addwalkroute (path) {Map.addoverlay (New Bmap.polyline (path, {strokecolor: ' black ', stroke opacity:0.7, Strokeweight:4, Strokestyle: ' Dashed ', enableclicking:false});}         function AddLine (path) {Map.addoverlay (New Bmap.polyline (path, {strokecolor: ' Blue ', strokeopacity:0.6, Strokeweight:5, enableClicking:false}));} 

In the above code, the callback function is set by the Onsearchcomplete property of Transitrouteoptions, which is called once the retrieval is complete. At the beginning of the callback function we first determine whether the retrieval is successful, if the success indicates that there is at least one bus plan to return, here we first through the result object to obtain the starting point and the end point, and then directly get the first scheme, traversing all the pedestrian lines and bus lines in the scheme and plotted on the map, Finally, we set a suitable map view according to the point of the bus line.

You will get the following effect in the browser:

When getting the result object, in addition to the callback function parameters obtained, can also be obtained through the Transitroute GetResults method, it should be noted that because the search process is asynchronous, the following code will not get the result:

Transit.search (' Xidan ', ' Summer Palace '); var res = Transit.getresults ();  Undefined

Because the search results are not returned immediately after the call to the searching method is completed. The developer can call this method in the callback function to get the result immediately, or it can be called when the callback function finishes executing some time before trying to get the result data.

Custom Scenario Description

The complete scenario description can be obtained through Transitrouteplan's getdescription, but it can be done via the data interface if the developer wants to define the description in its own way. For example:

var transit = new Bmap.transitroute (' Beijing ', {onsearchcomplete:function (result) {if (transit.getstatus () = = BMap            _status_success) {//Get start and end information from the result object var start = Result.getstart (). title;                        var end = Result.getend (). title;            Get the first solution directly var plan = Result.getplan (0);                        Gets the sum of the number of walking lines and bus lines used to traverse var total = plan.getnumroutes () + plan.getnumlines ();            var description = [' from ' + start];            var addendtitle = true; for (var i = 0, i < total; i++) {if (i% 2 = = 0) {//I is even//                            A walk describes the logical if (I/2 = = 0) {if (Plan.getroute (I/2). Getdistance (false) = = 0) {                        Description = [' From '];                        }}//Handle last Walk description logic if (I/2 = = Plan.getnumroutes ()-1) { if (Plan.getroute (I/2). Getdistance (false) = = 0) {Addendtitle = false; }} if (Plan.getroute (I/2). Getdistance (False) > 0) {des                    Cription.push (' walk about ' + Plan.getroute (I/2). Getdistance (True) + ' to ');                    }} else {//I is an odd var line = Plan.getline ((i-1)/2);                    if (i = = 0) {Description.push (Line.getgetonstop (). Title + ', ');                            } if (i > 0) {if (Plan.getroute ((i-1)/2). Getdistance (False) > 0) {                        Description.push (Line.getgetonstop (). Title + ', ');                    }} description.push (' Ride ' + line.title + ', ');                    Description.push (' after ' + line.getnumviastops () + ' station '); Description.push (' in ' + line.getgetOffstop (). Title + ' Stop Off, '); }} if (Addendtitle) {Description.push (end + ').            ‘); }//Replace the comma var descriptionstr = Description.join (") that may appear at the end of the position. Replace (/\uff0c$/, '.        ‘); }}); Transit.search (' Peking University ', ' Beijing Jiaotong University ');

The contents of variable descriptionstr are: "From Peking University walk about 60 meters to the Simon of Peking University, take the Express 106 (Central Party School North Gate-Tin Village North Road), after 6 stations in the Chinese Academy of Agricultural Sciences Station, take 26 (two Li-li-West gate), after 4 station at Beijing Jiaotong University station alight. ”。

Explanation of callback function

In the first few examples we used the Onsearchcomplete callback function, and the following callback functions are provided in the API, and their meanings and triggering times are as follows:

      • Onmarkersset: If a rendered map is set, the API will trigger this function when the callout is automatically added.
      • Onpolylinesset: If a rendered map is set, the API will trigger this function when the route overlay is automatically added.
      • Oninfohtmlset: If a render map is set, this function is triggered when the user taps the callout pop-up information window.
      • Onresultshtmlset: If the render sidebar is set, this function is triggered when the API fills up the HTML.

Baidu Map API detailed bus navigation

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.