如何使用 react-native-maps 中的自定义按钮转到我当前的位置?

How to go to my current location using custom button in react-native-maps?

我在 android 上使用 react-native-maps。我放了一个自定义按钮,点击它应该转到提供的坐标(我当前的位置)

<MapView
          ref={(map) => { this.map = map; }}
          provider={PROVIDER_GOOGLE}
          style={{ height: '100%', width: '100%' }}
          annotations={markers} 
          showsUserLocation={true}
          showsMyLocationButton={true}
          initialRegion={this.state.region}
          onRegionChangeComplete={this.onRegionChange}
        >

我的按钮 -

<TouchableOpacity onPress={this.gotToMyLocation} style={[Style.alignJustifyCenter, {
          width: 60, height: 60,
          position: "absolute", bottom: 20, right: 20, borderRadius: 30, backgroundColor: "#d2d2d2"
        }]}>
          <Image
            style={{ width: 40, height: 40 }}
            source={Images.myLocation}
          />
        </TouchableOpacity>

gotToMyLocation 方法 -

gotToMyLocation(){
    console.log('gotToMyLocation is called')
    navigator.geolocation.getCurrentPosition(
      ({ coords }) => {
        console.log("curent location: ", coords)
        console.log(this.map);
        if (this.map) {
          console.log("curent location: ", coords)
          this.map.animateToRegion({
            latitude: coords.latitude,
            longitude: coords.longitude,
            latitudeDelta: 0.005,
            longitudeDelta: 0.005
          })
        }
      },
      (error) => alert('Error: Are location services on?'),
      { enableHighAccuracy: true }
    )
  }

console.log(this.map) 总是显示未定义。

我想在点击按钮时将地图移动到我的当前位置。

实际上,我发现了一个愚蠢的错误,即绑定该方法会使它起作用。可能对某人有用。 this.gotToMyLocation = this.gotToMyLocation.bind(this);

移动你的函数 gotToMyLocation:

如果使用 Class - 在 class 之前 render()

如果使用函数 - 使用函数 gotToMyLocation(){...} 而不要使用这个

默认 my location 按钮

      showsUserLocation={true}
      showsMyLocationButton={true}

示例:

        <MapView
          provider={PROVIDER_GOOGLE}
          showsUserLocation={true}
          showsMyLocationButton={true}
          style={{
            ...StyleSheet.absoluteFillObject,
            width: '100%',
          }}
          initialRegion={{
            latitude: targetLocation.latitude,
            longitude: targetLocation.longitude,
            latitudeDelta: 0.0922,
            longitudeDelta: 0.0421,
          }}>

自定义按钮

    <MaterialIcons
      style={style.myLocationIcon}
      name="my-location"
      onPress={() => {
        dispatch(settingActions.getLocation());
        mapRef.current.animateToRegion({
          latitude: myLatitude,
          longitude: myLongitude,
          latitudeDelta: 0.0922,
          longitudeDelta: 0.0421,
        });
      }}
    />

为此你需要定义mapRef

export const mapRef = React.createRef();

return(
    <MapView
      ref={mapRef}

动画

mapRef.current.animateToRegion({ 将在您从一个位置切换到另一个位置时处理动画。