Search code examples
javascriptgoogle-mapsreact-nativereact-reduxreact-native-maps

React-Native-Maps: How to animate to coordinate?


I am using the following code with no success:

//Inside of NativeBase Container

        <MapView.Animated
           ref="map"
           style = {styles.map}
           showsUserLocation = {true}
           zoomEnabled = {true}
           showsMyLocationButton = {true}
           showsCompass = {true}
           showScale = {true}
           showsIndoors = {true}
           mapType = {this.state.mapTypes[this.state.mapTypeCode]}
        />

//Inside of componentDidMount of the class

navigator.geolocation.getCurrentPosition(
  (position) => {
    var initialPosition = JSON.stringify(position.coords);
    this.setState({position: initialPosition});

    let tempCoords = {
      latitude: Number(position.coords.latitude),
      longitude: Number(position.coords.longitude)
    }

    this.refs.map.animateToCoordinate(tempCoords, 1);

  }, function (error) { alert(error) },

);

But an error occurs saying there is no such function animateToCoordinate.


Solution

  • I've had some issues where this.refs is undefined, unless I bind a reference to this in the constructor to the function I am using this.refs in. In your case, try this:

    constructor(props) {
        super(props);
        this._getCoords = this._getCoords.bind(this);
        this.state = {
            position: null
        };
    }
    
    componentDidMount() {
        this._getCoords();
    }
    
    _getCoords = () => {
        navigator.geolocation.getCurrentPosition(
            (position) => {
                var initialPosition = JSON.stringify(position.coords);
                this.setState({position: initialPosition});
                let tempCoords = {
                    latitude: Number(position.coords.latitude),
                    longitude: Number(position.coords.longitude)
                }
                this._map.animateToCoordinate(tempCoords, 1);
              }, function (error) { alert(error) },
         );
    };
    
    render() {
        return (
             <MapView.Animated
                 ref={component => this._map = component}
              />
        );
    
    }
    

    Although using string refs is still possible, I believe that is legacy now, so I've also updated the MapView ref to the newer way. See: Ref Example