js 实现高德地图轨迹播放
时间: 2023-12-28 21:05:22 浏览: 28
要实现高德地图轨迹播放,可以使用高德地图 JavaScript API 中提供的 Polyline 类和 Marker 类。具体实现步骤如下:
1. 获取轨迹数据
首先需要获取轨迹数据,可以从后台接口获取或者从本地文件读取。轨迹数据一般是经纬度坐标数组,例如:
```
var path = [
[116.405289,39.904987],
[116.406289,39.904987],
[116.407289,39.904987],
//...
];
```
2. 创建地图对象
使用高德地图 JavaScript API 创建地图对象,例如:
```
var map = new AMap.Map('mapContainer', {
zoom: 14,
center: [116.397428, 39.90923]
});
```
其中 `mapContainer` 是地图容器的 ID,`zoom` 是地图缩放级别,`center` 是地图中心点坐标。
3. 创建轨迹 Polyline
使用 Polyline 类创建轨迹线段,例如:
```
var polyline = new AMap.Polyline({
map: map,
path: path,
showDir: true,
strokeColor: '#3366FF',
strokeOpacity: 1,
strokeWeight: 5,
strokeStyle: 'solid'
});
```
其中 `map` 是地图对象,`path` 是轨迹经纬度坐标数组,`showDir` 表示是否显示箭头,`strokeColor` 表示轨迹线段颜色,`strokeOpacity` 表示轨迹线段透明度,`strokeWeight` 表示轨迹线段宽度,`strokeStyle` 表示轨迹线段样式。
4. 创建播放 Marker
使用 Marker 类创建播放 Marker,例如:
```
var marker = new AMap.Marker({
map: map,
position: path[0],
icon: new AMap.Icon({
size: new AMap.Size(32, 32),
image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png'
})
});
```
其中 `map` 是地图对象,`position` 是 Marker 的位置,`icon` 是 Marker 的图标。
5. 实现轨迹播放
使用 JavaScript 的 `setInterval` 函数实现轨迹播放,例如:
```
var index = 0; // 当前播放到的轨迹点索引
var interval = setInterval(function() {
if (index >= path.length) {
clearInterval(interval);
return;
}
marker.setPosition(path[index]);
index++;
}, 1000);
```
其中 `index` 表示当前播放到的轨迹点索引,`interval` 表示定时器句柄。每隔一段时间,将 Marker 的位置设置为当前轨迹点的位置,同时将 `index` 加 1。当 `index` 大于等于轨迹点数组的长度时,停止定时器。
完整代码示例:
```
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>高德地图轨迹播放</title>
<style>
html, body, #mapContainer {
width: 100%;
height: 100%;
margin: 0;
}
</style>
<script src="https://webapi.amap.com/maps?v=1.4.15&key=您的高德地图密钥"></script>
</head>
<body>
<div id="mapContainer"></div>
<script>
var path = [
[116.405289,39.904987],
[116.406289,39.904987],
[116.407289,39.904987],
[116.408289,39.904987],
[116.409289,39.904987],
[116.410289,39.904987],
[116.411289,39.904987],
[116.412289,39.904987],
[116.413289,39.904987],
[116.414289,39.904987]
];
var map = new AMap.Map('mapContainer', {
zoom: 14,
center: [116.397428, 39.90923]
});
var polyline = new AMap.Polyline({
map: map,
path: path,
showDir: true,
strokeColor: '#3366FF',
strokeOpacity: 1,
strokeWeight: 5,
strokeStyle: 'solid'
});
var marker = new AMap.Marker({
map: map,
position: path[0],
icon: new AMap.Icon({
size: new AMap.Size(32, 32),
image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png'
})
});
var index = 0;
var interval = setInterval(function() {
if (index >= path.length) {
clearInterval(interval);
return;
}
marker.setPosition(path[index]);
index++;
}, 1000);
</script>
</body>
</html>
```
注意替换代码中的高德地图密钥。