【问题标题】:react native - react-native-maps initialRegion not workreact native - react-native-maps initialRegion 不起作用
【发布时间】:2017-10-25 05:09:53
【问题描述】:

我使用 react-native-maps 为 iOS 设备集成了 Google 地图。我有一个问题,在我重新渲染地图后initialRegion 不起作用。

我的应用程序仅包含 2 个组件:来自 react-native-mapsMapView 和一个 Button。点击按钮显示或隐藏地图。

这是我的代码:

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)
}

第一次加载地图,一切正常。但是,当我隐藏地图并通过单击按钮再次显示它时,它会呈现一个随机区域:

{ 
  longitude: 0,
  latitudeDelta: 0.0004935264587338631,
  latitude: 0,
  longitudeDelta: 0.00027760863304138184 
}

我试过 cacheEnabled 等于 truefalse 但没有帮助。如果您有任何建议,请告诉我。提前谢谢!

【问题讨论】:

    标签: javascript ios google-maps react-native react-native-maps


    【解决方案1】:

    当你第一次加载页面时,它会调用initialRegion,当你隐藏显示地图时,它不会再次调用initialRegion函数,因为之前已经加载了地图,所以你需要在隐藏/显示方法上调用函数和通过以下方法设置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 =&gt; { 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** } }            
              >
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-06
      • 1970-01-01
      • 1970-01-01
      • 2020-10-04
      • 1970-01-01
      • 1970-01-01
      • 2017-10-12
      相关资源
      最近更新 更多