Google Maps API提供了Marker
类来表示地图上的标记点。要实现标记的平滑移动效果,需要通过JavaScript逐步更新标记的位置,而不是一次性设置新位置。
setInterval
或requestAnimationFrame
实现动画这是最基础的方法,通过定时器逐步更新标记位置。
// 初始化地图
const map = new google.maps.Map(document.getElementById('map'), {
zoom: 13,
center: {lat: 51.501, lng: -0.142}
});
// 创建标记
const marker = new google.maps.Marker({
position: {lat: 51.501, lng: -0.142},
map: map
});
// 目标位置
const targetPosition = {lat: 51.503, lng: -0.135};
// 动画参数
const duration = 2000; // 动画持续时间(毫秒)
const steps = 60; // 动画步数
const stepTime = duration / steps;
let currentStep = 0;
// 计算每一步的增量
const latIncrement = (targetPosition.lat - marker.getPosition().lat()) / steps;
const lngIncrement = (targetPosition.lng - marker.getPosition().lng()) / steps;
// 启动动画
const animation = setInterval(() => {
if (currentStep >= steps) {
clearInterval(animation);
return;
}
const currentPosition = marker.getPosition();
const newPosition = new google.maps.LatLng(
currentPosition.lat() + latIncrement,
currentPosition.lng() + lngIncrement
);
marker.setPosition(newPosition);
currentStep++;
}, stepTime);
为了使移动更自然,可以使用缓动函数:
function easeInOutQuad(t) {
return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;
}
function animateMarker(marker, targetPosition, duration) {
const startPosition = marker.getPosition();
const startTime = performance.now();
function animate(currentTime) {
const elapsed = currentTime - startTime;
const progress = Math.min(elapsed / duration, 1);
const easedProgress = easeInOutQuad(progress);
const newLat = startPosition.lat() +
(targetPosition.lat - startPosition.lat()) * easedProgress;
const newLng = startPosition.lng() +
(targetPosition.lng - startPosition.lng()) * easedProgress;
marker.setPosition(new google.maps.LatLng(newLat, newLng));
if (progress < 1) {
requestAnimationFrame(animate);
}
}
requestAnimationFrame(animate);
}
// 使用示例
animateMarker(marker, targetPosition, 2000);
如果要沿着路径移动,可以使用折线上的点:
function moveAlongPath(marker, path, duration) {
const startTime = performance.now();
const pathLength = path.length;
function animate(currentTime) {
const elapsed = currentTime - startTime;
const progress = Math.min(elapsed / duration, 1);
const index = Math.floor(progress * (pathLength - 1));
if (index < pathLength - 1) {
const segmentProgress = (progress * (pathLength - 1)) % 1;
const currentPoint = path[index];
const nextPoint = path[index + 1];
const newLat = currentPoint.lat() +
(nextPoint.lat() - currentPoint.lat()) * segmentProgress;
const newLng = currentPoint.lng() +
(nextPoint.lng() - currentPoint.lng()) * segmentProgress;
marker.setPosition(new google.maps.LatLng(newLat, newLng));
requestAnimationFrame(animate);
} else {
marker.setPosition(path[pathLength - 1]);
}
}
requestAnimationFrame(animate);
}
requestAnimationFrame
代替setInterval
以获得更好的性能问题1:标记移动不流畅
requestAnimationFrame
问题2:移动结束后位置不准确
问题3:移动过程中地图卡顿
没有搜到相关的文章