React-Native-Maps: How to animate to coordinate?
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
Unfortunately now animateToCoordinate is deprecated and if you want to do the same, you should use animateCamera or animateToRegion instead.
render() {
return (
<MapView style = {styles.maps}
ref = {(mapView) => { _mapView = mapView; }}
initialRegion = {{
latitude: 6.8523,
longitude: 79.8895,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421,
}}
/>
<TouchableOpacity
onPress = {() => _mapView.animateToRegion({
latitude: LATITUDE,
longitude: LONGITUDE
}, 1000)}>
<Text>Tap</Text>
</TouchableOpacity>
)
}
In my case I used animateToCoordinate() like follows and it works for me:
var _mapView: MapView;
render() {
return (
<MapView style = {styles.maps}
ref = {(mapView) => { _mapView = mapView; }}
initialRegion = {{
latitude: 6.8523,
longitude: 79.8895,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421,
}}
/>
<TouchableOpacity
onPress = {() => _mapView.animateToCoordinate({
latitude: LATITUDE,
longitude: LONGITUDE
}, 1000)}>
<Text>Tap</Text>
</TouchableOpacity>
)
}