最近在做前端高德地图对接web的js开发, 设计到系统中车辆轨迹的运行,以及需要根据车辆行驶,
让车自动调整车头方向。
**给大家看一个效果:**
方法如下:
第一步:初始化Marker:
//生成车辆当前位置点标记
getCurMarker(curlnglat) {
this.trackMark = new AMap.Marker({
offset: new AMap.Pixel(-13, -26),
map: this.map,
icon: this.icon, //图片最好选择长方形的,方形的
autoRotation: false, //true不生效
angle: 0
});
this.trackMark.setPosition(curlnglat) //当前位置点
this.trackMark.setLabel({
content: "<span style='color:red;font-weight: bold;font-size: 16px' class='idDay'>" + 车牌号+ "</span>", //设置文本标注内容
});
**//给车的marker添加一个自定义的唯一class属性。 用于控制改变哪个style.重要 !!!!!!!**
this.trackMark.dom.classList.add('car-track-marker');
return this.trackMark;
}
加完属性后的页面中会显示。
接下来就是写跳转车头方向的算法:
第一步:
假设当前车辆经纬度设为oldPos对象,下一个经纬度点设为lnglat对象。
那么现在前后有两个点位信息,就可以获取车头方向角度数。
//计算角度angle
calAngle(oldPos, lnglat) {
if (oldPos.lng && oldPos.lat && lnglat.lng && lnglat.lat) {
let nDegree = calcRotateAngle(oldPos.lng, oldPos.lat, lnglat.lng, lnglat.lat);
if (nDegree < 0) {
nDegree = 360 + nDegree;
}
nDegree = parseInt(nDegree.toFixed(0));
return nDegree;
}
return 0;
},
//角度获取
function calcRotateAngle(x1, y1, x2, y2) {
var d = 0;
x1 = x1 * Math.PI/180;
y1 = y1 * Math.PI/180;
x2 = x2 * Math.PI/180;
y2 = y2 * Math.PI/180;
d = Math.sin(x1) * Math.sin(x2) + Math.cos(x1) * Math.cos(x2) * Math.cos(y2 - y1);
d = Math.sqrt(1 - d * d);
if(d != 0) {
d = Math.cos(x2) * Math.sin(y2 - y1) / d;
if(d > 1.0) {
d = 1;
}
else if(d < -1.0) {
d = -1;
}
d = Math.asin(d) * 180/Math.PI;
if(x1 - x2 > 0.000001 && y1 - y2 < 0.000001) {
d = -d - 180;
}
else if(x1 - x2 > 0.000001 && y1 - y2 > 0.000001){
d = -d + 180;
}
d = d % 360;
}
return d;
},
//车头方向调整,label方向不改
directCar() {
//计算车辆角度
let nDegree = this.calAngle(oldPos, lnglat)
if (nDegree > 0) {
//设置车头角度
trackMarker.setAngle(nDegree);
**//只让车辆图片旋转,不影响lable中内容。**
$(".car-track-marker>.amap-icon").css({
'transform':'rotate('+nDegree+'deg)'
})
}
}
最后用trackMarker.setPosition(lnglat)去改变车的位置,用moveTo()的话,setAngel会失效
大功告成!!!
效果如图一。