mapbox动态路径
class AddRunningRoute{
declare map: any
declare geojsonData: any
declare sourceId: string
declare lineRunningBackground: string
declare lineRunningDashed: string
declare timer: any
declare isAnimation: boolean
declare dashArraySequence: Array<any>
declare step: number
declare lineColor: string
declare lineWidth: number
constructor(option: {
map:any,
isAnimation: boolean,
geojsonData: any,
lineColor?: string,
lineWidth?: number
}) {
this.map = option.map
this.geojsonData = option.geojsonData
this.isAnimation = option.isAnimation
this.lineColor = option?.lineColor || 'rgba(0,255,255,1)'
this.lineWidth = option?.lineWidth || 6
this.sourceId = 'line-running' + Date.now()
this.lineRunningBackground = 'line-running-background' + Date.now()
this.lineRunningDashed = 'layer-running-dashed' + Date.now()
this.step = 10
this.dashArraySequence = [
[0, 4, 3],
[0.5, 4, 2.5],
[1, 4, 2],
[1.5, 4, 1.5],
[2, 4, 1],
[2.5, 4, 0.5],
[3, 4, 0],
[0, 0.5, 3, 3.5],
[0, 1, 3, 3],
[0, 1.5, 3, 2.5],
[0, 2, 3, 2],
[0, 2.5, 3, 1.5],
[0, 3, 3, 1],
[0, 3.5, 3, 0.5]
]
this.init()
}
private init(){
this.map.addSource(this.sourceId, {
type: 'geojson',
data: this.geojsonData
})
this.map.addLayer({
type: 'line',
source: this.sourceId,
id: this.lineRunningBackground,
paint: {
'line-color': this.lineColor,
'line-width': this.lineWidth,
'line-opacity': 1
}
})
if(this.isAnimation){
this.map.addLayer({
type: 'line',
source: this.sourceId,
id: this.lineRunningDashed,
paint: {
'line-color': '#fff',
'line-width': this.lineWidth,
'line-dasharray': [0, 4, 3]
}
})
this.animate()
}
}
private animate(){
const animateDashArray = (timestamp: number)=> {
const newStep = parseInt(
String((timestamp / 50) % this.dashArraySequence.length), 10
)
if (newStep !== this.step) {
this.map.setPaintProperty(
this.lineRunningDashed,
'line-dasharray',
this.dashArraySequence[this.step]
)
this.step = newStep
}
this.timer = requestAnimationFrame(animateDashArray)
}
animateDashArray(0)
}
on(callback){
if(this.isAnimation){
this.map.on('click',this.lineRunningDashed,(e)=>{
callback(e)
const coordinates = e.features[0].geometry.coordinates
this.map.panTo(coordinates)
})
}else {
this.map.on('click',this.lineRunningBackground,(e)=>{
callback(e)
const coordinates = e.features[0].geometry.coordinates
this.map.panTo(coordinates)
})
}
}
destroy(){
if(this.timer){
cancelAnimationFrame(this.timer)
}
if(this.map?.getSource(this.sourceId)){
this.map.removeLayer(this.lineRunningBackground)
if(this.isAnimation){
this.map.removeLayer(this.lineRunningDashed)
}
this.map.removeSource(this.sourceId)
}
}
}
export default AddRunningRoute