我使用 react-native-maps
为 iOS 设备集成了 Google map 。我遇到一个问题,即在我重新渲染 map 后 initialRegion
不起作用。
我的应用程序只包含 2 个组件:来自 react-native-maps
的 MapView
和一个 Button
。单击按钮可显示或隐藏 map 。
这是我的代码:
render() {
return (
<View style={styles.mapContainer}>
{this.renderMap()}
<TouchableOpacity
onPress={this.onButtonPress.bind(this)}
style={styles.showMapButtonContainer}>
<Text style={styles.showMapButtonText}>Show and Hide Map</Text>
</TouchableOpacity>
</View>
);
}
renderMap() {
if (this.state.showMap) {
return (
<MapView
provider={PROVIDER_GOOGLE}
style={styles.map}
initialRegion={{
latitude: 37.78825,
longitude: -122.4324,
latitudeDelta: LATITUDE_DELTA,
longitudeDelta: LONGITUDE_DELTA,
}}
cacheEnabled={true}
onRegionChangeComplete={this.onRegionChangeComplete.bind(this)}
>
</MapView>
);
} else {
return <View style={styles.map}/>;
}
}
onButtonPress() {
this.setState({
showMap: !this.state.showMap,
})
}
onRegionChangeComplete(region) {
console.log("new region", region)
}
第一次加载 map ,一切正常。但是,当我隐藏 map 并通过单击按钮再次显示它时,它会呈现一个随机区域:
{
longitude: 0,
latitudeDelta: 0.0004935264587338631,
latitude: 0,
longitudeDelta: 0.00027760863304138184
}
我试过 cacheEnabled
等于 true
和 false
但没有帮助。如果您有任何建议,请告诉我。预先感谢您!
最佳答案
当你第一次加载页面时,它会调用 initialRegion
,当你隐藏显示 map 时,它不会再次调用 initialRegion
函数,因为 map 已经加载过,所以你需要在隐藏/显示方法上调用函数并通过以下方法设置initialRegion
this.map.setNativeProps({ region });
或
this.map.animateToRegion({
latitude: this.props.latitude,
longitude: this.props.longitude,
longitudeDelta: LONGITUDE_DELTA ,
latitudeDelta: LATITUDE_DELTA
}, 1)}
你需要添加 ref={ref => { this.map = ref; } }
如下所示,在函数中你得到 this.map
作为引用
<MapView
ref={ref => { this.map = ref; } }
initialRegion={{
latitude: 37.78825,
longitude: -122.4324,
latitudeDelta: LATITUDE_DELTA,
longitudeDelta: LONGITUDE_DELTA,
}}
onRegionChangeComplete={(region) => { **somefuncation** } }
>
关于javascript - react native - react-native-maps initialRegion 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46924415/