Search code examples
javascriptreact-nativereact-native-maps

Using a method on a component in React Native Maps


I am trying to use the animateMarkerToCoordinate method on a marker in React Native Maps.

The documentation proposes the following:

componentWillReceiveProps(nextProps) {
  const duration = 500

  if (this.props.coordinate !== nextProps.coordinate) {
    if (Platform.OS === 'android') {
      if (this.marker) {
        this.marker._component.animateMarkerToCoordinate(
          nextProps.coordinate,
          duration
        );
      }
    } else {
      this.state.coordinate.timing({
        ...nextProps.coordinate,
        duration
      }).start();
    }
  }
}

render() {
  return (
    <MapView initialRegion={...}>
      <Marker.Animated
        ref={marker => { this.marker = marker }}
        coordinate={this.state.coordinate}
      />
    </MapView>
  );
}

I tried to implement this in my code. The code in the documentation is written in ancient React (componentWillReceiveProps is deprecated)

<MapView.Marker.Animated draggable
                coordinate={this.state.playerMarkerPositionFuture}
                title={"Player"}
                description={"Player marker!"}
                image={require('./assets/player_map_icon_small_transparent.png')}
                onDragEnd={(event) => this.setState({ playerMarkerPositionFuture: event.nativeEvent.coordinate })}
                onDragStart={this.movePlayerMarker()}
                />

...

movePlayerMarker = () => {
    this.marker._component.animateMarkerToCoordinate(
      nextProps.coordinate,
      1000
    );
  }

However I get this error:

undefined is not an object (evaluating '_this.marker._component')

Found an better example here.


Solution

  • Remove _component from animation marker method.Just write following

    this.marker.animateMarkerToCoordinate(
              nextProps.coordinate,
              duration
            );
    

    instead of

    this.marker._component.animateMarkerToCoordinate(
              nextProps.coordinate,
              duration
            );
    

    It will work.