uber/react-map-gl getMap & exposed Mapbox API

2.4k Views Asked by At

I'm using the following code snippet to try to access the MapBox API from uber react-map-gl: 4.0.2 using mapbox-gl v0.50.0.

 import MapGL from 'react-map-gl';
 export default class App extends Component 
 {
   constructor(props) {
    super(props);
   this.mapRef= React.createRef();
   }
   componentDidMount() 
   {
      let data = this.mapRef.getMap().getBounds(); <----
   } 
   render() {
    <MapGL
    {...viewport}
    width="100%"
    height="100%"
    mapStyle={MapStyle}
    onViewportChange={this._updateViewport}
    ref={map => this.mapRef = map}
    mapboxApiAccessToken={TOKEN} >
   }
 }

if I try to access any other methods like getStyle/getSource and others raise an error "is not a function" & "Cannot read property 'version' of undefined". Am i Doing something wrong or Not all MapBox Api methods are not available through the getMap() method ?

Thanks

2

There are 2 best solutions below

1
On

If you can get the map object correctly then all the functions should be exposed including getStyle. getSource didn't work for me either, it could be that using mapStyle is not counted as a source? Not sure about this last bit.

0
On

I use this to get the initial map boundaries.

    getMapBoundaries = () => {
    // Get map boundaries
    const myMap = this.mapRef.getMap(); 
    console.log(myMap.getBounds());
    const mapBoundaries = myMap.getBounds();
    this.setState({ mapBoundaries })
  }

  componentDidMount = () => this.getMapBoundaries();

I also noticed that the import for 'react-map-gl' should be

import ReactMapGL from 'react-map-gl';

Why the error? It seems you are not using a return function in the componentDidMount method.