仅在 iOS 上使用 onRegionChangeComplete 时 react-native-maps 中的错误

A bug in react-native-maps when using onRegionChangeComplete only on iOS

我正在使用 react-native-maps,这似乎只是 iOS 上的一个错误。
如果我调用 onRegionChangeComplete,iOS 会永远向下移动屏幕。我的代码如下!

class PickLocation extends Component {
  state = {
    userLocation: {
      latitude: 0,
      longitude: 0,
      latitudeDelta: 0.015,
      longitudeDelta: 0.0121
    },
    moved: false,
    firstTime: true
  };

  async componentDidMount() {
    // Place the screen where user stands after loading
    this.whereAmI();
    console.log(this.state);
  }

  whereAmI = () => {
    Geolocation.getCurrentPosition(
      position => {
        this.setState(prevState => {
          return {
            userLocation: {
              ...prevState.userLocation,
              latitude: position.coords.latitude,
              longitude: position.coords.longitude
            }
          };
        });
      },
      err => {
        console.log(err);
        alert("Getting current Location Failed!");
      }
    );
  };

  onRegionChangeCompleteHandler = region => {
    console.log(region);
    if (this.state.firstTime) {
      this.setState({
        firstTime: false
      });
      return;
    }

    this.setState({
      userLocation: region,
      moved: true
    });
  };

  render() {
    return (
      <View style={styles.container}>
        <MapView
          provider={PROVIDER_GOOGLE}
          initialRegion={this.state.userLocation}
          region={this.state.userLocation}
          style={styles.map}
          showsUserLocation={true}
          onRegionChangeComplete={this.onRegionChangeCompleteHandler}
        />
      </View>
    );
  }
}


我认为发生这种情况是因为 regionChange 之后的坐标与实际坐标不同。
请帮我修复一下。

react-native-mapsios 都没有错误,这是 React 的自然行为方式。

Region props 一直触发,而 onRegionComplete props 仅在坐标更改后触发一次。

map bouncing/moving marker non-stop 的发生是因为调用 setState 需要一些时间来更新 state,这会导致冲突。您需要在 onRegionComplete 之后用新坐标更新地图区域,而 region 仍然有旧坐标,因此地图移动到新坐标并且 region 一直触发,迫使地图 return 回到旧坐标,这也会导致再次开火 onChangeComplete 然后地图开始永远在新旧坐标之间跳动。

解决方案是

  • 首先删除region={this.state.userLocation}并且不要再使用region prop,这不仅是因为它是您问题的原因,也是因为您没有不需要用状态来控制你的地图。
  • 其次initialRegion坐标与userLocation坐标分开,这也是弹跳问题之一,如initialRegionMap Componenet 首次安装时使用新坐标触发一次,而 region 具有坐标 {0,0}(由您的州设置)。 所以你这样做

    state ={
      initialRegion: {} //empty object
      }
    
    
    whereAmI = () => {
         Geolocation.getCurrentPosition(
              position => {
              this.setState({
                 initialRegion: position.coords
             });
             },
            err => {
             console.log(err);
             alert("Getting current Location Failed!");
             }
           );
        };
    
       ..... map props 
    
       initialRegion={this.state.initialRegion}
    

并且 onRegionComplete 可以安全地设置 userLocation's state