隨筆- 66 文章- 0 評論- 348
【百度地圖API】如何制作公交線路的搜索?如331路
摘要:
從A點到B點的公交導航大家都知道怎么做了,那么單獨查詢331路公交車的公交路線,如何制作呢?我們一起來學習一下~
-----------------------------------------------------------------------------------------------------------------
一、創建地圖和網頁樣式
兩句話建立地圖:
var map = new BMap.Map("container");
map.centerAndZoom(new BMap.Point(116.322, 40.003), 12);
然后把網頁結構搭建好。有一張圖片,一個文本框,一個按鈕。還有一張地圖。
CSS樣式我就直接給出了,這里就不多說了。大家可以去W3Cschool學習~~這是我最愛的網站:http://www.w3school.com.cn/css/index.asp
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>搜索331路公交</title>
<script type="text/javascript" src="http://api.map.baidu.com/api?v=1.2"></script>
</head>
<body>
<p><img src="http://map.baidu.com/img/logo-map.gif" /><span style="display:inline-block;width:200px;"> </span><input type="text" value="331" id="busId" />路公交 <input type="button" value="查詢" onclick="busSearch();" /></p>
<div style="clear:both"> </div>
<div style="float:left;width:600px;height:500px;border:1px solid gray" id="container"></div>
<div id="results" style="float:left;width:300px;height:500px;font-size:13px;"></div>
</body>
</html>
<script type="text/javascript">
var map = new BMap.Map("container");
map.centerAndZoom(new BMap.Point(116.322, 40.003), 12);
</script>
效果圖:
二、公交線路接口
先來看看百度地圖API給出的接口類參考:
使用構造函數,創建一個公交線路的查詢。並在renderOptions里設置查詢成功后,結果的展示。
var busline = new BMap.BusLineSearch(map,{
renderOptions:{map:map,panel:"results"},
onGetBusListComplete: function(result){
if(result) {
var fstLine = result.getBusListItem(0);//獲取第一個公交列表顯示到map上
busline.getBusLine(fstLine);
}
}
});
創建一個函數,獲取到文本框中輸入的“331”路公交車,(還可以輸入104,或者987,注意,只能支持數字)然后,執行查詢。
function busSearch(){
var busName = document.getElementById("busId").value;
busline.getBusList(busName);
}
效果圖:
全部源代碼:
按 Ctrl+C 復制代碼