来源哔哩哔哩视频:百度地图路径规划_哔哩哔哩_bilibili
源 码
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>百度地图路径规划</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=ek5SWXmBxc7eXrlsIE0nvYqZKYqoHXsE"></script>
<style>
#bdmap-contaniner{
width: 700px;
height: 500px;
border: 1px solid black;
}
</style>
</head>
<body>
<button class="createMap">加载地图</button>
<br/>
<label for="startPoint">
起点:<input type="text" id="startPoint" value="冠县"/>
</label>
<label for="endPoint">
终点:<input type="text" id="endPoint" value="聊城"/>
</label>
<select >
<option value="car">驾车</option>
<option value="bus">公交</option>
<option value="step">步行</option>
</select>
<br/>
<button class="route">开启规划路径</button>
<div id="bdmap-contaniner"></div>
<script>
//页面元素
var startPoint_input=document.querySelector('#startPoint');
var endPoint_input=document.querySelector('#endPoint');
var routeType_select=document.querySelector('select');
var bdmap=null;
document.querySelector('.createMap').onclick= function () {
bdmap=new BMap.Map('bdmap-contaniner');
var point = new BMap.Point(115.43, 36.48);
bdmap.centerAndZoom(point, 15);
bdmap.addControl(new BMap.NavigationControl());
var centerMarker=new BMap.Marker(point);
centerMarker.addEventListener('click', function (eve) {
var opts = {
width : 250, // 信息窗口宽度
height: 100, // 信息窗口高度
title : "地点坐标" // 信息窗口标题
};
var infoWindow_content='当前位置:('+eve.point.lng+','+eve.point.lat+')';
var infoWindow = new BMap.InfoWindow(infoWindow_content, opts); // 创建信息窗口对象
bdmap.openInfoWindow(infoWindow, bdmap.getCenter()); // 打开信息窗口
});
bdmap.addOverlay(centerMarker);
};
//路径规划
document.querySelector('.route').onclick= function () {
var startPoint_value=startPoint_input.value;
var endPoint_value=endPoint_input.value;
var routeType_select_value=routeType_select.value;
switch (routeType_select_value){
case 'car':{
//驾车路线规划
var driving = new BMap.DrivingRoute(bdmap, {
renderOptions: {
map: bdmap,
autoViewport: true
}
});
//绘制
driving.search(startPoint_value, endPoint_value);
}
break;
case 'bus':{
var transit = new BMap.TransitRoute(bdmap, {
renderOptions: {
map: bdmap,
autoViewport: true
}
});
transit.search(startPoint_value, endPoint_value);
}break;
case 'step':{
var walk = new BMap.WalkingRoute(bdmap, {
renderOptions: {map: bdmap}
});
walk.search(startPoint_value, endPoint_value);
}
break;
}
}
</script>
</body>
</html>