2 回答
TA贡献1893条经验 获得超10个赞
问题是,目前,您的地图将在您为 pin 坐标发出 API 请求之前呈现。如果这是使用 react-native-maps,他们的文档指出在初始渲染后更改 initialRegion 不会导致地图更改:
在组件安装后更改 [the initialRegion] 属性不会导致区域更改。 https://github.com/react-native-community/react-native-maps/blob/master/docs/mapview.md
您需要:
等到您有 API 响应来渲染地图,或者
使用初始区域的估计值渲染地图,并在 API 调用完成且状态更新后更新地图位置。
选项1:
if (this.state.loading) {
// Better loading logic here
return <Text>Loading...</Text>
}
return (
<MapView
style={styles.map}
initialRegion={{
latitude: posts.lat,
longitude: posts.lng,
latitudeDelta: 0.04,
longitudeDelta: 0.05,
}}
>
</MapView>
);
第二种选择:
// You need to add region to state.
getPosts() {
axios
.get('myAPI')
.then(response => {
this.setState({
post: response.data,
region: {
latitude: response.data.lat,
longitude: response.data.long,
latitudeDelta: 0.04,
longitudeDelta: 0.05,
}
loading: false
});
});
}
render() {
return (
<MapView
style={styles.map}
initialRegion={{
latitude: posts.lat,
longitude: posts.lng,
latitudeDelta: 0.04,
longitudeDelta: 0.05,
}}
region={this.state.region}
>
...
</MapView>
);
}
加分项:如果您使用animateToRegion. https://github.com/react-native-community/react-native-maps/blob/master/docs/mapview.md#methods
希望这可以帮助!
TA贡献1847条经验 获得超7个赞
我以前遇到过这个问题,我像这样修复了它们。
首先,您应该在导航到地图视图之前获取远程数据。
并且您应该使用道具或导航参数将 latlng 数据发送到 MapView。
其次,您应该initialRegion
通过传递的数据进行设置。
添加回答
举报