调整大小后,是否需要在Mapbox GL中重新绘制我的图层?

时间:2017-11-11 19:43:38

标签: javascript html css reactjs mapbox-gl

我看到Mapbox GL地图出现奇怪的行为:

https://mapbox-gl-test.herokuapp.com/

当我调整窗口大小时,我的数据层(彩色城市)消失了。但它们不再可见了。当您单击它们时,仍然会显示弹出窗口。

这是否与我调整Mapbox GL元素的方式有关?由于简单性,我将所有元素(htmlbody#rootmapContainer)放在width: 100%height: 100%

我已经在我的反应组件上创建了一个onResize方法,我在其中触发this.map.resize(),但这没有帮助。当我console.log我的this.map.getStyle().layers时,我仍然创建了所有图层。

所有代码都是开放的:here。相关组件看起来像这样:

class MapGL extends PureComponent {
  constructor (props) {
    super(props)

    this.state = {
      isInitialized: false
    }

    this.initMap = this.initMap.bind(this)
    this.addGeoJsonLayer = this.addGeoJsonLayer.bind(this)
    this.onClick = this.onClick.bind(this)
    this.onResize = this.onResize.bind(this)
  }

  componentDidMount () {
    this.initMap()
    window.addEventListener('resize', this.onResize)
  }

  onResize () {
    this.map.resize()
  }

  addGeoJsonLayer () {
    const layers = this.map.getStyle().layers
    const placeLabelLayer = layers.find(layer => layer['source-layer'] === 'place_label').id

    this.map.addLayer({
      'id': 'municipalities',
      'type': 'fill',
      'source': {
        'type': 'geojson',
        'data': this.props.data
      },
      'layout': {},
      'paint': {
        'fill-color': {
          type: 'identity',
          property: 'color'
        },
        'fill-opacity': 1
      }
    }, placeLabelLayer)

    this.setState({ isInitialized: true })
  }

  onClick (e) {
    const centerOfMass = TurfCenterOfMass(e.features[0].geometry)
    new MapboxGL.Popup()
      .setLngLat(centerOfMass.geometry.coordinates)
      .setHTML(this.getPopupContent(e.features[0].properties))
      .addTo(this.map)
  }

  getPopupContent (properties) {
    return `
      <h4 class="mapboxgl-popup-title">
        ${properties.municipality}
      </h4>
      <div class="mapboxgl-popup-text">
        ${format('.2%')(properties.ratio_total)} Männeranteil
      </div>
    `
  }

  initMap () {
    if (!this.mapContainer || this.map) {
      return false
    }

    MapboxGL.accessToken = MAPBOX_ACCESS_TOKEN

    this.map = new MapboxGL.Map({
      container: this.mapContainer,
      style: MAPBOX_STYLE_URL,
      center: this.props.center
    })

    this.map.fitBounds(this.props.bBox, {
      padding: 10
    })

    this.map.on('load', this.addGeoJsonLayer)
    this.map.on('click', 'municipalities', this.onClick)

    return true
  }

  render () {
      return (
        <div
          className={containerStyle}
          ref={(ref) => { this.mapContainer = ref }}
        />
      )
  }
}

0 个答案:

没有答案