通過百度地圖獲取公交線路的站點坐標的js代碼
2024-05-06 14:21:57
供稿:網友
最近做百度地圖的模擬數據,需要獲取某條公交線路沿途站點的坐標信息,貌似百度沒有現成的API,因此做了一個模擬頁面,工具而已,IE6/7/8不支持
代碼如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>獲取公交站點坐標</title>
<style type="text/css">
html,body{ height: 100%;}
#results,#coordinate{ display: inline-block; width: 45%; min-height: 200px; border:1px solid #e4e4e4; vertical-align: top;}
</style>
<script src="http://api.map.baidu.com/api?v=1.3" type="text/javascript"></script>
</head>
<body>
<p><label for="busId">公交線路:</label><input type="text" value="521" id="busId" /><input type="button" id="btn-search" value="查詢" /></p>
<div id="results"></div>
<div id="coordinate"></div>
<script type="text/javascript">
(function(){
var tempVar;
var busline = new BMap.BusLineSearch('武漢',{
renderOptions:{panel:"results"},
onGetBusListComplete: function(result){
if(result) {
tempVar = result;//此時的結果并不包含坐標信息,所以getCoordinate函數不能在此調用。通過跟蹤變量,坐標是在onGetBusListComplete之后才被百度的包添加進來的
busline.getBusLine(result.getBusListItem(0));
}
},
// api文檔中一共有四個回調,除了onGetBusListComplete和onBusLineHtmlSet之外,還有onBusListHtmlSet和onGetBusLineComplete,
// 經過測試只有在onBusLineHtmlSet這一步(線路格式化完畢)的時候,才會將坐標添加到tempVar中
// 所以上面busline.getBusLine(result.getBusListItem(0));是必須的,不然沒有辦法獲得坐標列表
onBusLineHtmlSet : function(){
try{
getCoordinate(tempVar);
}catch(e){
}
}
});
function getCoordinate(result){
var coordinate = document.getElementById("coordinate");
var stations = result['0']._stations;
var html = [];
stations.forEach(function(item){
html.push('<li>' + item.name + ' ' + item.position.lng + ' ' + item.position.lat + '</li>');
});
coordinate.innerHTML = '<ul>' + html.join('') + '</ul>';
}
document.getElementById('btn-search').onclick = function(){
busline.getBusList(document.getElementById("busId").value);
}
})();
</script>
</body>
</html>
獲取反向線路的話就把var stations = result['0']._stations;改為var stations = result[xx]._stations;整理了一下:
代碼如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>獲取公交站點坐標</title>
<style type="text/css">
html,body{ height: 100%;}
#results,#coordinate{ display: inline-block; width: 45%; min-height: 200px; border:1px solid #e4e4e4; vertical-align: top;}
</style>