首页 > 解决方案 > 在 ReactJS 中集成 Mapbox 的错误

问题描述

本质上,我想执行以下操作\

1. As soon as the webpage loads, Get the current coordinates of the user using geoLocation API
2. Then initialize the map in mapbox with center as the users current co-ordinates.

我的代码如下

class MapContainer extends React.Component {
    constructor(props) {
       super(props);
       // Initializing the lat , lng and map to NULL in the state
       this.state = { lat: null , lng: null , zoom: 15, map : null};
       this.mapContainer = React.createRef();
    }

    mapInit = ()=>{
       const map = new mapboxgl.Map({
       container: this.mapContainer.current,
       style: 'mapbox://styles/mapbox/streets-v11',
       center: [this.state.lng, this.state.lat],
       zoom: this.state.zoom
   });

   this.setState({map : map});
 }

 getCurrCoords = ()=>{
     console.log("hello world");
     window.navigator.geolocation.getCurrentPosition(
    (position)=> { 
        this.setState({lat : position.coords.latitude , lng : position.coords.longitude});
        this.mapInit();
        return;
    },
    (err) => { console.log(err); }
  );
 }

  componentDidMount = async ()=>{
 // Get the users current Location
    await this.getCurrCoords();
    await this.mapInit();


    this.state.map.on('move', () => {
    this.setState({
        lng: this.state.map.getCenter().lng,
        lat: this.state.map.getCenter().lat,
        zoom: this.state.map.getZoom().toFixed(2)
      });

    });
 }

render() {
   return (
     // this is the reference being created. And we can do DOM manipulation to this component
    <>
       <div className="sidebar">
          Longitude: {this.state.lng} | Latitude: {this.state.lat} | Zoom: {this.state.zoom}
       </div>
       <div ref={this.mapContainer} className='map-container'></div>
    </>
  )
 }
}

由于 componentDidMount 是一个异步函数

所以首先它应该等待 getCurrCoords 完成更新状态中的 lat 和 lng

之后它应该调用 mapInit 函数并等待它完成它的工作。

但我收到以下错误。 错误图像

这意味着 componentDidMount() 没有等待 getCurrCoords 函数。我对吗?还是有一些我还不知道的更深层次的问题。

将 ComponentDidMount() 作为异步函数和地理定位 API 是否可以在等待下工作?

标签: reactjsmapbox-gl-jssetstatereact-state

解决方案


推荐阅读