I have a MapView in my React Native app but I'm not sure how I can set its initial location to the device's geolocation. Right now I'm creating a ref
and updating it with the device's coordinates using the geolocation
package.
This isn't working though, because whenever I open the app on my phone the region coordinates is 0.0, 0.0
as set initially with useRef
. The ref
is being updated when my phone moves, the map position just isn't changing. If I zoom out, I can see a marker on my location from the showsUserLocation
prop. What's wrong with the way I'm trying to update the map's region?
const region = useRef({
latitude: 0.0,
longitude: 0.0,
latitudeDelta: 0.0922,
longitudeDelta: 0.0922,
});
useEffect(() => {
const watchId = Geolocation.watchPosition(
position => {
const payload = {
lat: position.coords.latitude,
lng: position.coords.longitude,
};
axios
.post('http:localhost:3000/location/update', payload)
.then(res => {
region.current = {
latitude: position.coords.latitude,
longitude: position.coords.longitude,
latitudeDelta: 0.0922,
longitudeDelta: 0.0922,
};
})
},
err => console.log(err.response),
);
<MapView
initialRegion={region}
initialCamera={{
center: {
latitude: region.current.latitude,
longitude: region.current.longitude,
},
}}
showsUserLocation={true}
/>
Try using state and also add region
rather than only just intialRegion
const [region,setRegion] = useState({ latitude: 0.0, longitude: 0.0, latitudeDelta: 0.0922, longitudeDelta: 0.0922, }); useEffect(() => { const watchId = Geolocation.watchPosition( position => { const payload = { lat: position.coords.latitude, lng: position.coords.longitude, }; axios.post('http:localhost:3000/location/update', payload).then(res => { setRegion({ latitude: position.coords.latitude, longitude: position.coords.longitude, latitudeDelta: 0.0922, longitudeDelta: 0.0922, }) }) }, err => console.log(err.response), ); <MapView initialRegion={region} region={region} initialCamera={{ center: { latitude: region.current.latitude, longitude: region.current.longitude, }, }} showsUserLocation={true} />
Hope it helps
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.