const points = [
[125.548848, 40.736387]
// ...........
// 数据集
]
// 轨迹
const line = new LineString(points).transform('EPSG:4490', 'EPSG:3857')
const routeCoords = line.getCoordinates()
const routeLength = routeCoords.length
// 轨迹线要素
const routeFeature = new Feature({
type: 'route',
geometry: line
})
// 轨迹点要素
const geoMarker = new Feature({
type: 'geoMarker',
geometry: new Point(routeCoords[0])
})
// 创建样式
const styles = {
route: new Style({
stroke: new Stroke({
width: 3,
color: 'blue'
})
}),
geoMarker: new Style({
image: new StyleCircle({
radius: 5,
snapToPixel: false,
fill: new Fill({
color: 'red'
})
})
})
}
let animating = false
let speed
let now
// 创建要素图层
const vectorLayer = new VectorLayer({
source: new VectorSource({
features: [routeFeature, geoMarker]
}),
style: function (feature) {
if (animating && feature.get('type') === 'geoMarker') {
return null
}
return styles[feature.get('type')]
}
})
window.olMap.addLayer(vectorLayer)
// 监听事件
function moveFeature(event) {
const vectorContext = getVectorContext(event)
// const vectorContext = event.vectorContext
const frameState = event.frameState
if (animating) {
const elapsedTime = frameState.time - now
const index = Math.round((speed * elapsedTime) / 1000)
if (index >= routeLength) {
stopAnimation(true)
return
}
const currentPoint = new Point(routeCoords[index])
const feature = new Feature(currentPoint)
vectorContext.drawFeature(feature, styles.geoMarker)
}
window.olMap.render()
}
// 开始动画
function startAnimation() {
if (animating) {
stopAnimation(false)
} else {
animating = true
now = new Date().getTime()
speed = 5
geoMarker.setStyle(null)
vectorLayer.on('prerender', moveFeature)
window.olMap.render()
}
}
// 停止动画
function stopAnimation(ended) {
animating = false
const coord = ended ? routeCoords[routeLength - 1] : routeCoords[0]
geoMarker.getGeometry().setCoordinates(coord)
vectorLayer.un('prerender', moveFeature)
}
startAnimation()
vue3 + openlayers---实现轨迹回放prerender
于 2024-05-25 22:20:13 首次发布