首页 > 解决方案 > 地图标记不会加载到 componentDidMount

问题描述

我有一张从视口坐标获取用户位置的地图,然后它使用这些坐标从 API 中获取标记。问题是我的标记只有在我移动地图后才会出现。我对我缺少的东西感到困惑:

componentDidMount(){
        this.getInitialPosition();
        this.fetchLocations();
        this.getMarkers();
    }

然后我的函数来确定用户的位置:

getInitialPosition = () => {
        navigator.geolocation.getCurrentPosition(position => {
            let newViewport = {
                height: "100vh",
                width: "100vw",
                latitude: position.coords.latitude,
                longitude: position.coords.longitude,
                zoom: 15
            }
            this.setState({
                viewport: newViewport
            });
        });
    }

然后我从我的 API 中获取标记:

fetchLocations = () => {
        fetch(`http://localhost:3000/locations/${this.state.viewport.latitude}/${this.state.viewport.longitude}`)
        .then(resp => resp.json())
        .then(locations => this.setState({locations}))
    }

最后是标记:

getMarkers = () => {
        return this.state.locations.map(location => {
            return (
                <Marker key={location.id} offsetLeft={-25} offsetTop={-70} latitude={parseFloat(location.lat)} longitude={parseFloat(location.lng)}>
                    <div className="marker-styles" onClick={() => {this.handleLocationClick(location.id)}} >
                        <p>{location.reviews}</p>
                    </div>
                </Marker>
            );
        });
    }

然后当我调用地图时:

                <MapGL
                    {...this.state.viewport}

                    onClick={this.mapClick}
                    attributionControl={false}
                    onViewportChange={this.onViewportChange}
                    mapboxApiAccessToken={TOKEN}
                    mapStyle="mapbox://styles/mapbox/streets-v10">
                    {this.getMarkers()}                        
                </MapGL>

我得到了地图,但我没有得到标记。有人可以指出我正确的方向吗?我认为问题在于我对 Promise 和组件生命周期的把握不牢,但老实说,我一直无法弄清楚这一点。我在这里粘贴了完整的(凌乱的)代码:https ://pastebin.com/j8dzYAsk

标签: javascriptreactjsmapbox-gl-jsreact-map-gl

解决方案


问题是getInitialPosition并且fetchLocations异步的——当你调用它们时,它们得到的数据还没有被获取getMarkers

首先,我让 getInitialPosition 返回一个 Promise,这样fetchLocations一旦它也返回由fetch

然后,只需使用 Promise.all 等待这两个 Promise 解决,一旦完成,您调用this.getMarkers

componentDidMount(){
    Promise.all([
        this.getInitialPosition(),
        this.fetchLocations()
    ]).then(this.getMarkers);
}
getInitialPosition = () => {
    return new Promise((resolve, reject) => {
        navigator.geolocation.getCurrentPosition(position => {
            let newViewport = {
                height: "100vh",
                width: "100vw",
                latitude: position.coords.latitude,
                longitude: position.coords.longitude,
                zoom: 15
            }
            this.setState({
                viewport: newViewport
            });
            resolve();
        });
    });
}
fetchLocations = () => {
    return fetch(`http://localhost:3000/locations/${this.state.viewport.latitude}/${this.state.viewport.longitude}`)
    .then(resp => resp.json())
    .then(locations => this.setState({locations}));
}

推荐阅读