What im trying to do is to implement a map feature to my app. To do that i have use react-native-maps and expo-location.
The map doesn't have any error, but when I open it, it shows me a part of the map and after 2-3 seconds shows me the current location marker.
import React,{ useState, useEffect, useRef} from 'react';
import MapView, {Marker, PROVIDER_GOOGLE} from 'react-native-maps';
import { StyleSheet, Image , Text, View} from 'react-native';
import * as Location from 'expo-location';
import {
LocationView ,
LocationBtn,
} from '../components/styles';
import { MaterialIcons } from '@expo/vector-icons';
const Map = (props) =>{
const [mapRegion, setMapRegion] = useState(null);
const _map = useRef(null)
useEffect(() => {
(async () => {
let { status } = await Location.requestForegroundPermissionsAsync();
if (status !== 'granted') {
setErrorMsg('Permission to access location was denied');
return;
}
console.log('status', status)
let location = await Location.getCurrentPositionAsync({});
setMapRegion({
longitude: location.coords.longitude,
latitude: location.coords.latitude,
longitudeDelta: 0.0922,
latitudeDelta: 0.0421
});
// mapRef.current.animateToRegion(mapRegion, 3 * 1000);
})();
}, [])
console.log(mapRegion)
return(
<View style={{ flex: 1}}>
<MapView
region={mapRegion}
provider={PROVIDER_GOOGLE}
style={styles.map}
mapType={props.mapType}
loadingEnabled={false}
initialRegion={mapRegion}
userInterfaceStyle='light'
showsTraffic={true}
ref={_map}
// zoomEnabled={true}
// onMapReady={mapRegion}
>
{mapRegion != null &&
<Marker
coordinate={mapRegion}
>
<Image source={require('../assets/marker.png')} style={{height: 90, width: 90}} />
</Marker>
}
</MapView>
<LocationView>
<LocationBtn
>
<MaterialIcons
name="my-location"
size={30}
color="black"
style={{alignSelf: 'center', marginTop: 13}}
/>
</LocationBtn>
</LocationView>
</View>
)
}
const styles = StyleSheet.create({
map: {
height: '100%',
},
})
export default Map;
How can I make it when the user opens the map, to show the current location maker immediately, without any delay.
The method Location.getCurrentPositionAsync({})is async, and depending on the device it can take a while to get the user's location.
You could fetch the user's location on the screen before and pass the location using props or navigation parameters.