// 初始化map
this.map = new AMap.Map(name, {
resizeEnable: true,
mapStyle: MAP_STYLE,
zoom: 11, // 初始化地图层级
// center: source && source.length ? source : [116.397428, 39.90923], // 初始化地图中心点
});
// 自定义maker
const makeIcon = (y, x) => {
const setCurrentMarker = (marker, y, x) => {
// 设置角度
let rotateDeg = 0;
if (source && source.length && target && target.length) {
const disX = Math.abs(Number(target[0]) - Number(source[0]));
const dixY = Math.abs(Number(target[1]) - Number(source[1]));
const tan = Math.tan(dixY / disX);
const result = Math.atan(tan) / (Math.PI / 180);
rotateDeg = Math.round(result);
// 判断区间
const sectionJudge = (source, target) => {
const x1 = source[0];
const y1 = source[1];
const x2 = target[0];
const y2 = target[1];
if (x2 > x1 && y2 >= y1) {
return 1;
} if (x2 >= x1 && y2 < y1) {
return 2;
} if (x2 < x1 && y2 <= y1) {
return 3;
} if (x2 <= x1 && y2 > y1) {
return 4;
}
return 5;
};
const section = sectionJudge(source, target);
if (section === 1) {
rotateDeg = 90 - rotateDeg;
} else if (section === 2) {
rotateDeg = 90 + rotateDeg;
} else if (section === 3) {
rotateDeg = 180 + (90 - rotateDeg);
} else if (section === 4) {
rotateDeg = 270 + rotateDeg;
}
}
// 自定义点标记内容
const markerContent = document.createElement('div');
// 点标记中的图标
const markerImg = document.createElement('img');
markerImg.className = 'currentMaker';
markerImg.src = carImg;
markerImg.style.transform = `rotate(${rotateDeg}deg)`;
markerContent.appendChild(markerImg);
// 当前位置卡片
const currentCard = trackData.result.last_point.card_info;
const markerSpan = document.createElement('div');
markerSpan.className = 'currentMarkerCard';
markerSpan.innerHTML = `<div class='info'>
<div>${currentCard.text}</div>
<div>${currentCard.time}</div>
</div>`;
markerContent.appendChild(markerSpan);
marker.setContent(markerContent); // 设置点标记内容
marker.setPosition([y, x]); // 设置点标记位置
};
let currentMarker = null;
if (x && y) {
currentMarker = new AMap.Marker({
position: new AMap.LngLat(y, x),
imageOffset: new AMap.Pixel(-13, -30),
});
setCurrentMarker(currentMarker, y, x);
}
return currentMarker;
};
// 添加marker
const currentMaker = makeIcon(currentLocation.lng, currentLocation.lat);
this.map.add(currentMaker);
问题描述:我有一张车头朝着正y轴方向的车辆图片,老板要求我根据路线的行径方向动态设置车头的朝向,而不是固定的朝上
解决办法:自定义车辆icon,设置图片的transform, 旋转的角度根据起点和终点的x和y的差值计算偏移角度
写在最后:代码不太完整,方案可能也不是最优的,欢迎提出问题和更优的解决方案