How to centre the map to show a user's current location when the map screen is opened? By following the expo documentation, it should be achieved with Expo Location API? However, the documentation is unclear. I took part of the code from expo Location documentation and implemented it in my Map Screen. So, how should I integrate it in MapView to execute the getCurrentPositionAsync method and centre the map accordingly when the map screen is opened?
import React, { useContext, useState, useEffect } from "react";
import MapView from "react-native-maps";
import styled from "styled-components";
import { Searchbar } from "react-native-paper";
import { View } from "react-native";
import * as Location from 'expo-location';
const Map = styled(MapView)`
height: 100%;
width: 100%;
`;
const SearchBarContainer= styled(View)`
padding: ${(props) => props.theme.space[3]};
position: absolute;
z-index: 999;
top: 20px;
width: 100%;
`;
export const MapScreen = ({navigation}) => {
const [location, setLocation] = useState(null);
const [errorMsg, setErrorMsg] = useState(null);
useEffect(() => {
(async () => {
let { status } = await Location.requestForegroundPermissionsAsync();
if (status !== 'granted') {
setErrorMsg('Permission to access location was denied');
return;
}
let location = await Location.getCurrentPositionAsync({});
setLocation(location);
})();
}, []);
return (
<>
<SearchBarContainer>
<Searchbar placeholder="location"/>
</SearchBarContainer>
<Map showsUserLocation={true}>
</Map>
</>
);};
I have been struggling with this issue for a couple of days as well and I find it very weird that even though the expo MapView can show your own location on the map, it cannot return your own coördinates.
Despite that, the problem can be fixed with the following solution.
expo install expo-location
import * as Location from 'expo-location'
const [location, setLocation] = useState({});
useEffect(() => {
(async () => {
let { status } = await Location.requestForegroundPermissionsAsync();
if (status !== 'granted') {
return;
}
let location = await Location.getCurrentPositionAsync({
accuracy: Location.Accuracy.Balanced,
enableHighAccuracy: true,
timeInterval: 5
});
setLocation(location);
})();
}, []);
<MapView ref={mapRef}>.... </MapView>
const mapRef = React.createRef();
const goToMyLocation = async () => {
mapRef.current.animateCamera({center: {"latitude":location.coords.latitude, "longitude": location.coords.longitude}});
}