react-leaflet mapboxgl集成无法正常工作

时间:2018-11-14 07:17:55

标签: reactjs leaflet mapbox mapbox-gl-js react-leaflet

按照此页面上的答案进行操作: Render mapbox vector tiles inside react-leaflet?

当我导出MapBoxGLLayer并将其导入我的主类时,

喜欢

import MapBoxGLLayer from './MapBoxGLLayer';

并尝试在我的渲染函数中访问它,例如:

<Map>
  <MapBoxGLLayer
    accessToken={MAPBOX_ACCESS_TOKEN}
    style='https://style.example.com/style.json'
  />
</Map>

我遇到了这个错误,它非常一致。

MapLayer.js:77 Uncaught TypeError: Cannot read property 'layerContainer' of undefined
at VectorgridLayer.get (MapLayer.js:77)
at VectorgridLayer.componentDidMount (MapLayer.js:38)

道具没有传单。

enter image description here

我不知道我在做什么错。

2 个答案:

答案 0 :(得分:1)

从您提到的答案中得到一些提示,我就能使其正常工作。
您的MapBoxGLLayer.js

import L from "leaflet";
import {} from "mapbox-gl-leaflet";
import PropTypes from "prop-types";
import { GridLayer, withLeaflet } from "react-leaflet";

class MapBoxGLLayer extends GridLayer {
  createLeafletElement(props){
    return L.mapboxGL(props);
  }
}

export default withLeaflet(MapBoxGLLayer);  

缺少的是withLeaflet HOC。

用法:

npm i mapbox-gl-leaflet  

将mapbox-gl-js和CSS添加到index.html

<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.51.0/mapbox-gl.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.51.0/mapbox-gl.css' rel='stylesheet' />  

// Import the MapBoxGLLayer component mentioned above.
class App extends Component {
  state = {
    center: [51.505, -0.091],
    zoom: 13
  };

  render() {
    return (
      <div>
        <Map center={this.state.center} zoom={this.state.zoom}>
          <MapBoxGLLayer
            accessToken={MAPBOX_ACCESS_TOKEN}
            style="mapbox://styles/mapbox/streets-v9"
          />
        </Map>
      </div>
    );
  }
}  

您可以在此处找到工作示例:https://codesandbox.io/s/ooypokn26y
添加您自己的mapbox令牌以查看其工作情况。

答案 1 :(得分:1)

这似乎是mapbox-gl-leaflet版本0.0.3中的错误,它是npm中的“最新”版本,并于两年前发布。

onRemove: function (map) {
    if (this._map.options.zoomAnimation) {
        L.DomEvent.off(this._map._proxy, L.DomUtil.TRANSITION_END, this._transitionEnd, this);
    }

    map.getPanes().tilePane.removeChild(this._glContainer);
    this._glMap.remove();
    this._glMap = null;
}

未定义对象this.map._proxy。解决方案是在React Map组件中使用zoomAnimation = {false}禁用缩放动画。那么该分支不会出现在mapbox-gl-leaflet中,并且不会收到此错误。

此问题已在GitHub的mapbox-gl-leaflet的master分支中解决: https://github.com/mapbox/mapbox-gl-leaflet/blob/954875e2e4269db313c99d522689bc08f4aadad2/leaflet-mapbox-gl.js

因此,请尝试更新您的库。