首页 > 解决方案 > react-native-maps:animateToRegion 不适用于区域或初始区域?

问题描述

简而言之:为什么 animateToRegion 不适用于 region 或 initialRegion?

我已经测试了这种行为,并注意到 animateToRegion 在 useEffect() => {}, []); 中使用时也不起作用
但是,如果我向 animateToRegion 添加一个带有功能的简单按钮,那么带有 region 或 initialRegion 的 animateToRegion 将起作用。如果我在 MapView 上为 onPress/onLongPress 设置动画,它也可以工作。

以下代码几乎是 MapView 的用法。fitToMarker() 基本上从用户或默认位置获取位置,然后将它们传递给 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>

“世博会”:“^43.0.0”,
“react-native-maps”:“0.28.0”,

为读者提供的解决方案由于使用with
而出现问题。有条件地使用解决: 需要拖动地图时不使用,需要初始化时使用onMapReadyinitialRegiononRegionChangeComplete
animateToRegion

标签: react-nativeexporeact-native-maps

解决方案


尝试useRef改用。这是一个工作示例:

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

推荐阅读