【问题标题】:react-native-maps: animateToRegion does not work with region or initialRegion?react-native-maps:animateToRegion 不适用于区域或初始区域?
【发布时间】:2021-12-10 16:38:38
【问题描述】:

简而言之:为什么 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",

为读者提供的解决方案
出现问题是因为将onMapReady 与initialRegion 一起使用。有条件地使用onRegionChangeComplete 解决了这个问题:
需要拖动地图时不使用,但需要初始animateToRegion时使用。

【问题讨论】:

    标签: react-native expo react-native-maps


    【解决方案1】:

    尝试改用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,
    });
    

    【讨论】:

    • 我已经尝试过 useRef 和 useState,最后我似乎使用了 useState。但是改变这些并没有帮助解决这个问题。不过谢谢你的回答。
    • 我确定你需要使用useRef。也许您可以添加一个 git repo 或现场演示,以便人们可以轻松地调试问题。以上对我有用。
    • 嘿,我注意到你使用了方法:“onRegionChangeComplete”。似乎该方法只需稍加调整即可完美运行,因此在将“onMapReady”与“initialRegion”一起使用时,我的问题不知何故存在。我改为使用 useRef。所以我通过您的回答找到了解决方案并将其标记为正确,但我想问的是“onRegionChangeComplete”首选方法还是您建议其他方法?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-29
    • 2015-12-23
    • 2021-06-23
    • 1970-01-01
    • 2021-11-09
    • 1970-01-01
    相关资源
    最近更新 更多