I am using expo location and I want to navigate into a map[ view page after I fetched the coords object. My goal is that when I press a button, I will be prompted to my location with zoom at an acceptable level...
The code are working for IOS, but android is crashing constantly. I am using expo go application. The following code receives a prop with the location from the EXPO location package and the initial region is set to the coords.
export default function Map({ route, navigation }) {
const { location } = route.params;
return (
<View style={styles.container}>
<MapView style={styles.map}
initialRegion={{
latitude: location?.coords.latitude,
longitude: location?.coords.longitude
}}
// minZoomLevel={10}
zoomEnabled={true}
showsUserLocation={true}
/>
</View>
);
}
In the fllowing code, I ask for the permissions and return true if I have the relevand approval. Than, in the handlePickupLocationOnMap
function I ask for permission and get the current position. Than, if I have the location, navigate to the map screen.
const [locationPermissionInformation, requestPermission] = useForegroundPermissions();
const verifyPermissions = async () => {
if (locationPermissionInformation.status === PermissionStatus.UNDETERMINED) {
const permissionResponse = await requestPermission();
return permissionResponse.granted;
}
if (locationPermissionInformation.status === PermissionStatus.DENIED) {
Alert.alert('You need to allow this app to get your location for a good use')
return false;
}
return true;
}
/**
* Use the location coords object and push it to the map aerial view
* Execute the navigation function only after the MapView has the location
*/
const handlePickupLocationOnMap = async () => {
let hasPermssion = await verifyPermissions();
if (!hasPermssion) {
return;
}
const location = await getCurrentPositionAsync();
location && navigate.navigate('MapView', { location });
};
While React Navigation share data between 2 screens. Data (params) are serialized (converted to string).
Android Google Map SDK expects coordinates to be FLOAT not serialized STRING values.
The solution is always cast coordinates values to FLOAT.
export default function Map({ route, navigation }) {
const { location } = route.params;
const getInitialRegion = () => {
// A defaul region of map. Mostly in area close to your userbase.
const initialRegion = {
latitude: 37.78825,
longitude: -122.4324,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421,
};
let latitude = location?.coords?.latitude;
let longitude = location?.coords.longitude;
if (latitude && longitude) {
// Imperatively, coordinates values must be FLOAT
latitude = parseFloat(latitude);
longitude = parseloat(latitude);
const region = { ...initialRegion, latitude, longitude };
return region;
}
return initialRegion;
};
const initialRegion = getInitialRegion();
return (
<View style={styles.container}>
<MapView
style={styles.map}
initialRegion={initialRegion}
// minZoomLevel={10}
zoomEnabled={true}
showsUserLocation={true}
/>
</View>
);
}