openlayers小车按坐标点循环匀速移动
以地图作为底图,实现一个小车在地图上按照指定轨迹匀速移动,并自动计算转向。之前看别人实现一个“全息路段”的项目,能够实时显示十字路口或者马路上的车的行驶轨迹(平滑转弯,衔接等),感觉很是炫酷,于是乎自己模仿了一个小demo,随便玩一下。可能有些地方的算法还不够精准,有待完善…
效果图:
代码如下:
data.js
let dataArr =[
[10836932.628965743, 4998172.218425438] ,
[10638182.82599503, 3781582.515392581] ,
[10897159.841987172, 3552719.105911153] ,
[11120000.530166456, 4986126.775821152] ,
[11360909.382252172, 4895785.956289009] ,
[11053750.595842887, 3420219.23726401] ,
[11294659.4479286, 3257605.7621061527] ,
[11565681.906525029, 4823513.300663294] ,
[11866817.971632171, 4757263.366339724] ,
[11535568.300014313, 3185333.1064804387],
[11812613.479912885, 3058855.959135439],
[12125794.987624314, 4721127.038526867],
[12402840.167522885, 4684990.710714009],
[12023408.725487886, 2926356.090488296],
[12300453.905386457, 2860106.1561647244],
[12643749.0196086, 4630786.218994724],
[12866589.707787886, 4510331.792951867],
[12547385.478774315, 2878174.3200711533],
[12932839.642111458, 2878174.3200711533],
[13113521.281175744, 3751468.908881867],
[13125566.723780029, 4739195.202433295],
[13691702.526181456, 5425785.43087758],
[13553179.936232172, 6112375.659321865],
[12920794.199507171, 5407717.266971151],
[12065567.774602886, 4974081.3332168665],
[12788294.330860028, 4895785.956289009],
]
export default{
dataArr
}
<template>
<div>
<div id="Map" ref="map"></div>
</div>
</template>
<script>
import VectorLayer from 'ol/layer/Vector';
import VectorSource from 'ol/source/Vector';
import Feature from 'ol/Feature';
import { Draw } from 'ol/interaction';
import { Style, Fill, Stroke, Circle, Icon } from 'ol/style';
import { transform, fromLonLat, toLonLat } from 'ol/proj';
import { Point,LineString } from "ol/geom";
import CAR from '../../assets/car.svg';
import { Map, View,interaction,events } from "ol";
import TileLayer from "ol/layer/Tile";
import { defaults as defaultControls } from "ol/control";
import XYZ from "ol/source/XYZ";
import dataArr from './data'
export default {
data() {
return {
map: this.$route.params.map,
layer: null,
interaction: null,
source: null,
feature: null,
coors: [],//路的转折点
carPoint: [],//车还要走的点
index: 0,//当前小车所在的路段
timer: null,
follow: false, //默认不聚焦
}
},
methods: {
//初始化地图
initMap(){
this.map = new Map({
target: "Map",
controls: defaultControls({
zoom: false
}).extend([]),
layers: [
new TileLayer(
{
source: new XYZ({
url:
"http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}"
// "http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}"
})
},
{ zoomOffset: 1 }
),
],
view: new View({
center: fromLonLat([108.522097, 37.272848]),
zoom: 4.7,
maxZoom: 4.7,
minZoom: 4.7
})
});
},
//添加矢量图层
async open() {
//画轨迹线
await this.drawLine()
//开始动
this.moveStart();
},
//轨迹线 把每个点连起来
drawLine(){
this.lineLayer = new VectorLayer({
source: new VectorSource({
features: []
})
});
this.map.addLayer(this.lineLayer);
let comDots = []
let wireFeature = null
dataArr.dataArr.forEach((item,index)=>{
comDots.push(item)
wireFeature = new Feature({
geometry:new LineString(comDots)
})
wireFeature.setStyle(
new Style({
stroke: new Stroke({ // 设置边的样式
color: 'rgb(21, 106, 158)',
width: 1
}),
}),
)
this.lineLayer.getSource().addFeatures([wireFeature]);
})
},
//创建小车这个要素
moveStart() {
//坐标转换
this.dotsData = dataArr.dataArr.map(item => {
return transform(
item,
'EPSG:3857',
'EPSG:4326',
);
});
//深复制车的位置,不在原数组改变,方便重新播放
this.carPoint = JSON.parse(JSON.stringify(this.dotsData));
//小车最初位置在第一个坐标点
this.feature = new Feature({
geometry: new Point(this.carPoint[0]),
})
this.feature.setStyle(new Style({
image: new Icon({
src: CAR,
scale:0.25,
anchor: [0.5, 0.5],
rotation: this.countRotate(),
})
}));
//添加车辆元素到图层
this.lineLayer.getSource().addFeature(this.feature);
this.timeStart();
},
//计时器开始
timeStart() {
this.timer = setInterval(() => {
if(this.index + 1 >= this.carPoint.length) {
//重头开始
this.index = 0;
//移除要素
this.lineLayer.getSource().removeFeature(this.feature);
clearInterval(this.timer);
//重复运动
this.open() //自动开启功能
return ;
}
//到转折点旋转角度
if(this.nextPoint() === this.carPoint[this.index + 1]) {
this.index++;
this.feature.getStyle().getImage().setRotation(this.countRotate());
}
//改变坐标点
this.feature.getGeometry().setCoordinates(fromLonLat(this.carPoint[this.index]));
}, 10);
},
//计算下一个点的位置
//这里的算法是计算了两点之间的点 两点之间的连线可能存在很多个计算出来的点
nextPoint() {
let index = this.index;
let p1 = this.map.getPixelFromCoordinate(fromLonLat(this.carPoint[index])); //获取在屏幕的像素位置
let p2 = this.map.getPixelFromCoordinate(fromLonLat(this.carPoint[index + 1]));
let dx = p2[0] - p1[0];
let dy = p2[1] - p1[1];
//打印可见 在没有走到下一个点之前,下一个点是不变的,前一个点以这个点为终点向其靠近
let distance = Math.sqrt(dx * dx + dy * dy)
if(distance <= 1) {
return this.carPoint[index + 1];
} else {
let x = p1[0] + dx / distance;
let y = p1[1] + dy / distance;
let coor = transform(
this.map.getCoordinateFromPixel([x, y]),
'EPSG:3857',
'EPSG:4326'
);
this.carPoint[index] = coor; //这里会将前一个点重新赋值 要素利用这个坐标变化进行移动
return this.carPoint[index];
}
},
//计算两点之间的角度 算旋转角度
countRotate() {
let i = this.index, j = i + 1;
if(j === this.carPoint.length) {
i--;
j--;
}
let p1 = this.carPoint[i];
let p2 = this.carPoint[j];
return Math.atan2( p2[0] - p1[0],p2[1] - p1[1]);
},
},
mounted(){
this.initMap();//初始化地图方法
this.open() //自动开启功能
}
}
</script>
<style lang="scss" scoped>
#Map{
width: 70vw;
height:100vh;
background: rgb(0,21,48);
}
.open-btn{
margin:10px;
}
.el-button{
position: relative;
z-index: 99;
}
</style>