Reputation: 95
there are a lot of example on how to use react-native-maps in a Class Component but i haven't found those with Stateless Component. I use Stateless Component to access the a global state. I need to move the camera view of the MapView from the initial region after i got the user's location, After searching in internet i somehow ends up with this code that is not working.
import React, { useState, useEffect, useRef } from 'react'
import MapView, { Marker, PROVIDER_GOOGLE } from 'react-native-maps';
...
const Explore = props => {
const [userCoords, setUserCoords] = useState({
latitude: 0,
longitude: 0
})
const mapRef = useRef(null);
onMapReady = () => {
getUserLocation()
}
getUserLocation = async () => {
Geolocation.getCurrentPosition(
async (position) => {
setUserCoords(position.coords)
mapRef.animateToRegion({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
})
},
async (error) => {
// See error code charts below.
console.log("Geolocation Error" + error.code, error.message);
},
{ enableHighAccuracy: true, timeout: 15000 }
);
}
return(
...
<MapView
ref={mapRef}
onMapReady={() => onMapReady()}
region={{
latitude: userCoords.latitude,
longitude: userCoords.latitude,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421,
showsUserLocation={true}>
...
</MapView>
)
...
export default Explore
Please help me~ Thank you
Upvotes: 2
Views: 3518
Reputation: 496
Instead of using mapRef.animateToRegion
you need to use mapRef.current.animateToRegion
Upvotes: 5