Home > Software design >  react-native-maps: animateToRegion does not work with region or initialRegion?
react-native-maps: animateToRegion does not work with region or initialRegion?

Time:10-26

In short: Why animateToRegion does not work with region or initialRegion?

I have tested this behaviour and noticed that animateToRegion also does not work while it is used in useEffect() => {}, []);
But if I add a simple button with function to animateToRegion then animateToRegion with region or initialRegion will work. And it also works if I animateToRegion onPress/onLongPress on MapView.

The following code is pretty much the usage of MapView. fitToMarker() basically takes location from user or from default location and then passes them to animateToRegionHolder().

const [mapRef, updateMapRef] = useState<MapView | null>(null);
  
const animateToRegionHolder = (lat: number, lng: number) => {
    if (mapRef) {
      mapRef.animateToRegion(
        {
          latitude: lat,
          longitude: lng,
          latitudeDelta: 0.2,
          longitudeDelta: 0.0421,
        },
        1000,
      );
    }
  };

<MapView
    ref={ref => updateMapRef(ref)}
    onMapReady={fitToMarker}
    onLongPress={e => choosePosition(e.nativeEvent.coordinate)}
    provider={PROVIDER_GOOGLE}
    style={[S.MapsStyles.mapView, defineMapContainerStyle()]}
        /**
         * This for some reason affects that fitToMarker will not work
         * But removing this will affect slight animation (which is not desired) on initial render
         * initialRegion={O.region}
         */
        >
<MapView>

"expo": "^43.0.0",
"react-native-maps": "0.28.0",

CodePudding user response:

Try using useRef instead. Here is a working example:

const mapRef = React.useRef<MapView >(null);
<MapView
  ref={mapRef}
  initialRegion={initialRegion}
  onRegionChangeComplete={handleRegionChange}
/>
mapRef.current?.animateToRegion({
  latitude: selectedCoordinates.lat,
  longitude: selectedCoordinates.lng,
  longitudeDelta: 0.004,
  latitudeDelta: 0,
});
  • Related