一、
单个点沿线运动主与之前的开发一样,都需要加入一些基础控件;我们需要在代码中通过坐标设置起点和终点;添加图标;生成路线,通过驾车实例获取点数据以进行移动轨迹的显示。
二、效果展示
三、源码
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
body,
html,
#allmap {
width: 100%;
height: 100%;
overflow: hidden;
margin: 0;
font-family: "微软雅黑";
}
</style>
<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=eZIflp2p4gzYF6E9O5H9EKyq471ic4cB"></script>
<title>单个标注点沿直线的轨迹运动</title>
</head>
<body>
<div id="allmap"></div>
</body>
</html>
<script type="text/javascript">
// 百度地图API功能
var map = new BMap.Map("allmap");
addMapControl();//向地图添加控件
map.centerAndZoom(new BMap.Point(106.729023,26.594216), 12);
function addMapControl() {
//向地图中添加缩放控件
var ctrl_nav = new BMap.NavigationControl({ anchor: BMAP_ANCHOR_TOP_LEFT, type: BMAP_NAVIGATION_CONTROL_LARGE });
map.addControl(ctrl_nav);
//向地图中添加缩略图控件
var ctrl_ove = new BMap.OverviewMapControl({ anchor: BMAP_ANCHOR_BOTTOM_RIGHT, isOpen: 1 });
map.addControl(ctrl_ove);
//向地图中添加比例尺控件
var ctrl_sca = new BMap.ScaleControl({ anchor: BMAP_ANCHOR_BOTTOM_LEFT });
map.addControl(ctrl_sca);
}
var myP1 = new BMap.Point(106.690216,26.676372); //起点
var myP2 = new BMap.Point(106.764955,26.558028); //终点
var myIcon = new BMap.Icon("http://lbsyun.baidu.com/jsdemo/img/Mario.png", new BMap.Size(32, 70), { //小车图片
//offset: new BMap.Size(0, -5), //相当于CSS精灵
imageOffset: new BMap.Size(0, 0) //图片的偏移量。为了是图片底部中心对准坐标点。
});
var driving2 = new BMap.DrivingRoute(map, { renderOptions: { map: map, autoViewport: true } }); //驾车实例
driving2.search(myP1, myP2); //显示一条公交线路
window.run = function () {
var driving = new BMap.DrivingRoute(map); //驾车实例
driving.search(myP1, myP2);
driving.setSearchCompleteCallback(function () {
var pts = driving.getResults().getPlan(0).getRoute(0).getPath(); //通过驾车实例,获得一系列点的数组
var paths = pts.length; //获得有几个点
var carMk = new BMap.Marker(pts[0], { icon: myIcon });
map.addOverlay(carMk);
i = 0;
function resetMkPoint(i) {
carMk.setPosition(pts[i]);
if (i < paths) {
setTimeout(function () {
i++;
resetMkPoint(i);
}, 100);
}
}
setTimeout(function () {
resetMkPoint(5);
}, 100)
});
}
setTimeout(function () {
run();
}, 1500);
</script>