Search code examples
react-nativereact-native-maps

React-Native-Maps don't seem to rerender once the geo location is acquired


I'm trying to create a simple app that loads a google map (using airbnb's react-native-maps library) and shows the user's current location. What I'm seeing is that the map always shows the default initial position rather than re-rendering once the user's location is acquired.

I'm using React 0.42 and testing only on iOS. Here is some code to clarify:

1.) I set an initial state

state = {
      region: {
        latitude: 52,
        longitude: 5,
        latitudeDelta: 0.0922,
        longitudeDelta: 0.0421
      }
  }

2.) I get the user's location within componentDidMount

componentDidMount() {
    navigator.geolocation.getCurrentPosition(
      (position) => {
        this.setState({
          region: {
            latitude: position.coords.latitude,
            longitude: position.coords.longitude,
            latitudeDelta: 0.01,
            longitudeDelta: 0.0011
          }
        });
      },
      (error) => alert(JSON.stringify(error)),
      {enableHighAccuracy: true, timeout: 20000, maximumAge: 1000}
    );
  }

3.) With render, I display the map with the initial region, and expect that region to change once the user's location is acquired

render() {
    return (
     <View style={{ flex: 1 }}>
       <View style={{backgroundColor: 'coral', height: 70, justifyContent: 'center', alignItems: 'center'}}>
         <Text>
            <Text>longitude: {this.state.region.longitude}</Text>
            <Text>latitude: {this.state.region.latitude}</Text>
        </Text>
       </View>
       <View style={styles.container}>
         <MapView
           provider={PROVIDER_GOOGLE}
           style={styles.map}
           initialRegion={this.state.region}
           region={this.state.region}
           onRegionChange={this.onRegionChange}
           onRegionChangeComplete={this.reloadEntities}
         />
       </View>
     </View>
   );
 }

Here is the onRegionChange, just updates the state with the new region, which I believe will cause a re-render

onRegionChange = (region) => {
  this.setState({ region });
}

NOTE: The longitude and latitude text values do update as the region on the map changes, and they have they are updated once the user's location is acquired.

So I'm a bit confused as to why the map does not change what it's showing once the user's location is acquired. Any help would be much appreciated!

Update: I've taken a look at this thread: https://github.com/airbnb/react-native-maps/issues/43 and it seems to revolve mainly around Android, but I did try to remove the enableHighAccuracy option with no luck.


Solution

  • It's also important to get rid of onRegionChangeComplete={this.reloadEntities}.

    Every time the region changes, react-native will reload and default back to the initial state you declared in your constructor.