效果图
// 通过GeoJSON方式增加图层数据
const layer = new VectorLayer({
source: new VectorSource({
features: new GeoJSON().readFeatures(
{
type: 'FeatureCollection',
features: [
{
type: 'Feature',
geometry: {
type: 'LineString',
coordinates: [
[117.283042, 31.86119],
[121.687899486, 31.24916171]
]
}
}
]
},
{
dataProjection: 'EPSG:4490',
featureProjection: 'EPSG:3857'
}
)
}),
style: [
new Style({
stroke: new Stroke({
color: '#f00',
width: 3,
lineDash: [0]
})
}),
new Style({
stroke: new Stroke({
color: '#ff0',
width: 3,
lineDash: [20, 27]
})
})
]
})
window.olMap.addLayer(layer)
// 设置图层样式 通过定时器setInterval实现动画效果
layer.getSource().getFeatures().forEach((item) => {
setInterval(() => {
let style = item.getStyle()
if (style == undefined) {
item.setStyle([
new Style({
stroke: new Stroke({
color: '#f00',
width: 3
})
}),
new Style({
stroke: new Stroke({
color: '#ff0',
width: 3,
lineDash: [20, 27],
lineDashOffset: 0
})
})
])
} else {
let lineDashOffset = item.getStyle()[1].getStroke().getLineDashOffset()
item.setStyle([
new Style({
stroke: new Stroke({
color: '#f00',
width: 3
})
}),
new Style({
stroke: new Stroke({
color: '#ff0',
width: 3,
lineDash: [15, 15],
lineDashOffset: lineDashOffset === 29 ? 0 : lineDashOffset + 1
})
})
])
}
}, 10)
})