Search code examples
react-nativereact-native-maps

React Native Maps onMapReady getMapBoundaries


I haven't been able to find anything to fix it. I'm using react-native maps

const finalMap = () => {

    return(
    <SafeAreaView style={styles.authContainerStyles}>
      <MapView
        style={styles.map}
        provider={PROVIDER_GOOGLE}
        region={{
          latitude:   !!userLocation ? userLocation.coords.latitude : 43.60271848664041,
          longitude: !!userLocation
          ? userLocation.coords.longitude
          : -116.20149258821509,
          latitudeDelta: 0.05,
          longitudeDelta: 0.05,
        }}
        onMapReady = {this.map.getMapBoundaries()}
      >

Solution

  • Try the below code or run this Snack here: https://snack.expo.io/Cu5qYmcZm

    function Map() {
      const [mapRef, updateMapRef] = useState(null);
      const getBoundaries = () => {
        if (mapRef === null) {
          return;
        }
        mapRef
          .getMapBoundaries()
          .then((res) => {
            console.log(res);
          })
          .catch((err) => console.log(err));
      };
      return (
        <View>
          <MapView
            ref={(ref) => updateMapRef(ref)}
            onMapReady={() => getBoundaries()}
          />
        </View>
      );
    }
    

    You need to store the ref to the map, so you can refer back to it later (when you check the boundaries). You could also store this in the state. Then after the map is ready, the event is fired and using the ref we can refer back to it and query the info about the boundaries.