Skip to content

电子围栏示例

示例

示例源码
tsx
import React, { useCallback, useEffect, useRef, useState } from 'react'
import ReactDOM from 'react-dom'
import { MbMap, MbTiandituLayer } from '@mapbox-react/core'

const App = () => {
  const [mapCenter] = useState([119.297868, 29.732983])
  const [zoom, setZoom] = useState(7)
  const [pitch, setPitch] = useState(45)
  const mapInst = useRef<any>()

  let map: any
  let layer: any
  const [show, setShow] = useState(true)

  const mapCreated = (mapbox: any) => {
    map = mapbox
  }
  const layerCreated = () => {
    initL7()
  }
  const update = useCallback(() => {
    setShow((s) => {
      layer.setVisibility(!s)
      layer.reRender()
      return !s
    })
  }, [setShow])
  const initL7 = () => {
    fetch(`https://mapbox-web.github.io/mapbox-react/json/wall.json`)
      .then((res) => res.json())
      .then((data) => {
        layer = new map.mapboxgl.supermap.L7Layer({ type: 'LineLayer' })
        const l7Layer = layer.getL7Layer()
        l7Layer.source(data).size(40).shape('wall').style({
          opacity: '0.8',
          sourceColor: '#0DCCFF',
          targetColor: 'rbga(255,255,255, 0)',
          heightfixed: true,
        })
        map.addLayer(layer)
      })
  }

  return (
    <div className="map-wrapper">
      <MbMap
        ref={mapInst}
        center={mapCenter}
        zoom={zoom}
        pitch={pitch}
        onCreated={mapCreated}
      >
        <button className="btn primary" onClick={update}>
          Show/Hide:{`${show}`}
        </button>
        <MbTiandituLayer types={['img', 'cva']} onCreated={layerCreated} />
      </MbMap>
    </div>
  )
}

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