【发布时间】: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