我有一张从视口坐标获取用户位置的地图,然后它使用这些坐标从 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