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 = React.useRef<MapView | null>(null);
const animateToRegionHolder = (lat: number, lng: number) => {
if (mapRef.current) {
mapRef.current.animateToRegion(
{
latitude: lat,
longitude: lng,
latitudeDelta: 0.2,
longitudeDelta: 0.0421,
},
1000,
);
}
};
<MapView
ref={mapRef}
onMapReady={fitToMarker}
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",
SOLUTION PRESENTED FOR READERS
The problem occurred because of using onMapReady with initialRegion. It was solved by using onRegionChangeComplete conditionally:
When dragging of map is needed it is not used, but when initial animateToRegion is needed it is used.