传单在React应用中使用新数据重新渲染地图

时间:2019-01-04 17:25:34

标签: reactjs leaflet maps

具有以下实现方式:

getCurrentMap() {
  const {currentlyActiveMap: {task, type, layout}} = this.mapStore
  if (this.currentMap) this.currentMap.eachLayer(layer => {
    this.currentMap.removeLayer(layer)
  })

  let centerX = 0
  let centerY = 0

  if (layout.image_width > layout.image_height) {
    centerX = layout.tile_size / 2
    centerY = (layout.tile_size * layout.image_height / layout.image_width) / 2
  } else {
    centerX = (layout.tile_size * layout.image_width / layout.image_height) / 2
    centerY = layout.tile_size / 2
  }

  this.currentMap = this.currentMap || Leaflet.map(this.map, {
    center: [-centerY, centerX],
    crs: Leaflet.CRS.Simple,
    minZoom: 0,
    maxZoom: layout.max_zoom_level + 1,
    maxBounds: [[layout.tile_size, -layout.tile_size], [-2 * layout.tile_size, 2 * layout.tile_size]],
    doubleClickZoom: false,
    attributionControl: false,
    zoom: 2
  })

  let currentLayer = Leaflet.tileLayer(`${layout.tiling_url}`)
  this.currentMap.addLayer(currentLayer)

  return (
    <Fragment>
      <button type='button' className={styles.mapPanelCreateButton} onClick={this.handleCreateTask}>
        <FaPlus/>
      </button>
    </Fragment>
  )
}


render() {
  const mapLayout = !!this.taskStore.loading || !this.mapStore.currentlyActiveMap
    ? <LoadingContainer transparent={true}/>
    : this.getCurrentMap()

  return (
    <Fragment>
      <div id='map' className={styles.mapPanelContainer} ref={map => this.map = map}></div>
      {mapLayout}
    </Fragment>
  )
}

我无法渲染地图,也无法更新/交换或更改地图中的数据(需要在自定义平铺图像和全局地图之间切换)。是说此实现存在本质上的问题,还是有更好的案例来实现这一目标?

一如既往地感谢所有方向,所以在此先感谢您!

另一个具有相同结果的实现:

Leaflet.tileLayer(`${layout.tiling_url}`).addTo(this.currentMap)

编辑:我也收到了臭名昭著的消息: 未捕获的错误:地图容器已经初始化。

1 个答案:

答案 0 :(得分:0)

所以我想我会回头并提供解决方案:

@jbccollins感谢您的建议,但是我需要更底层的自定义,而React-leaflet没有PR便无法提供。我很乐意贡献力量,但是我没有时间等待加入。

this.locationLayer = Leaflet.tileLayer('https://{s}.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}{r}.png')
this.floorPlanLayer = Leaflet.tileLayer(layout.tiling_url)

this.currentMap = Leaflet.map(this.map, options)
this.locationLayer.addTo(this.currentMap)

if (this.currentMap.hasLayer(this.locationLayer)) {
    this.currentMap.addLayer(this.floorPlanLayer)
    this.currentMap.removeLayer(this.locationLayer)
    this.currentLayer = this.floorPlanLayer
  } else {
    this.currentMap.addLayer(this.locationLayer)
    this.currentMap.removeLayer(this.floorPlanLayer)
    this.currentLayer = this.locationLayer
  }