javascript - 地图标记不会加载到 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
解决方案
问题是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}));
}
推荐阅读
- python - QPrintPreviewDialog 100% 缩放
- javascript - 使用到达路由器导航到 404 路由
- java - 可选的
> 不能申请 - html - 如何比较 JQuery 中的两个元素文本?
- android - Android Studio 尝试运行我的第一个 Hello World
- linux - 如何使用 xargs 将 ls 导入 cat 以便列出文件名?
- php - 如何从动态生成的 html 表单字段中检索值
- c++ - 虚拟析构函数,派生类中没有析构函数会怎样?
- c++ - 写入“array”时缓冲区溢出:可写大小为“1*4”字节,但可能写入“8”字节
- java - 解压http响应