首页 > 解决方案 > 仅在 iOS 上使用 onRegionChangeComplete 时 react-native-maps 中的错误

问题描述

我正在使用 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-nativereact-native-maps

解决方案


也没有错误react-native-mapsios它是自然的React行为方式。

Region props一直开火,而onRegionComplete props坐标改变后只开火一次。

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

解决方案是

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

    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


推荐阅读