Skip to content

Car Animation

Example

Example Source Code
tsx
import React, { useCallback, useEffect, useRef, useState } from 'react'
import ReactDOM from 'react-dom'
import { MbMap, MbTiandituLayer } from '@mapbox-react/core'
import EchartsLayer from 'echarts-layer'

const App = () => {
  const [mapCenter] = useState([125.2, 43.9])
  const [zoom, setZoom] = useState(11)
  const [pitch, setPitch] = useState(0)
  const mapInst = useRef<any>()

  let map: any
  const mapCreated = (mapbox: any) => {
    map = mapbox
  }

  const render = () => {
    initEchart(map)
  }

  const initEchart = (map: any) => {
    fetch(`https://mapbox-web.github.io/mapbox-react/json/changchunBus.json`)
      .then((res) => res.json())
      .then((data) => {
        const lines = Array.prototype.concat.apply(
          [],
          data.map((busLine) => {
            busLine.lineStyle.normal.color = '#000'
            busLine.effect = {
              constantSpeed: 60,
              show: true,
              trailLength: 0,
              symbolSize: 30,
              symbol: (function () {
                if (Math.round(Math.random() * 2) % 2) {
                  return 'image://https://mapbox-web.github.io/mapbox-react/images/blueCar.png'
                } else {
                  return 'image://https://mapbox-web.github.io/mapbox-react/images/redCar.png'
                }
              })(),
            }
            return busLine
          })
        )

        const option = {
          animation: false,
          GLMap: {
            roam: true,
          },
          series: [
            {
              type: 'lines',
              coordinateSystem: 'GLMap',
              polyline: true,
              data: lines,
              silent: true,
              lineStyle: {
                normal: {
                  opacity: 1,
                  width: 2,
                },
              },
              progressiveThreshold: 500,
              progressive: 100,
            },
            {
              type: 'lines',
              coordinateSystem: 'GLMap',
              polyline: true,
              data: lines,
              lineStyle: {
                normal: {
                  width: 0.2,
                },
              },
              effect: {
                constantSpeed: 60,
                show: true,
                trailLength: 0,
                symbolSize: 30,
              },
            },
          ],
        }
        const echartslayer = new EchartsLayer(map)
        echartslayer.chart.setOption(option)
      })
  }

  return (
    <div className="map-wrapper">
      <MbMap
        ref={mapInst}
        center={mapCenter}
        zoom={zoom}
        pitch={pitch}
        onCreated={mapCreated}
      >
        <MbTiandituLayer types={['vec', 'cva']} onCreated={render} />
      </MbMap>
    </div>
  )
}

ReactDOM.render(<App />, document.querySelector('#root'))