【发布时间】:2022-01-02 07:36:05
【问题描述】:
如何在地图屏幕打开时使地图居中以显示用户的当前位置?按照expo文档,应该用Expo Location API来实现吗?但是,文档不清楚。我从 expo Location 文档中获取了部分代码,并在我的地图屏幕中实现了它。那么,我应该如何将它集成到 MapView 中以执行 getCurrentPositionAsync 方法并在地图屏幕打开时相应地居中?
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>
</>
);};
【问题讨论】:
标签: javascript reactjs react-native expo react-native-maps