调用百度地铁图JS API示例
- 1使用之前也要申请百度地图JavaScript AP ak
- 2 添加一个div容器,用于地图的渲染位置
<div>
<select id=city>
<div>
<span>起始位置:</span>
<input type="text" id=startname value="起点"/>
=>
<span>终点位置:</span>
<input type="text" id=endname value="终点"/>
<input type="button" id=btn value="搜索路线">
</div>
</select>
</div>
<div><span>地铁图</span></div>
<div id="container">
</div>
3 代码
<script type="text/javascript">
var list = BMapSub.SubwayCitiesList;
var subway ;
$(function(){
InitSelect(list);//初始化城市选择框
InitMap(131,null);
});
//城市选择框改变事件,用于城市地图切换
$("#city").change(function(){
//var a = $("#city :selected").text();
//console.log(a);
InitMap($("#city").val(),"西单");
});
//初始化城市选择框
function InitSelect(list){
for (var key in list) {
var obj = document.getElementById("city");
var option = document.createElement("option");//创建option节点
option.innerText = list[key].name;
option.value=list[key].citycode;
obj.appendChild(option);
}
};
// 获取地铁数据-初始化地铁图
function InitMap(citycode,startname){
subway = new BMapSub.Subway('container',citycode);
subway.setZoom(0.7);
var zoomControl = new BMapSub.ZoomControl({
anchor: BMAPSUB_ANCHOR_TOP_LEFT,
offset: new BMapSub.Size(10,100)
});
subway.addControl(zoomControl);
//添加站名点击事件
subway.addEventListener('tap', function(e) {
///alert('您点击了"' + e.station.name + '"站');
var marker = new BMapSub.Marker(e.station.name);//, {icon: startIcon}
subway.addMarker(marker);
subway.setCenter(e.station.name)
var a=$("#startname").val();
var b=$("#endname").val();
if(a==""||a=="起点"){
$("#startname").val(e.station.name);
}
else
{
$("#endname").val(e.station.name);
}
subway.setZoom(0.7);
});
if(startname!=null){
var marker = new BMapSub.Marker(startname);//, {icon: startIcon}
subway.addMarker(marker);
subway.setCenter(startname);
subway.setZoom(1.5);
}
};
$("#btn").click(function(){
//alert("点击事件");
var drct = new BMapSub.Direction(subway,false);
var a=$("#startname").val();
var b=$("#endname").val();
drct.search(a, b);
});
</script>
asd.gif
网友评论