Pat*_*k89 2 javascript reactjs react-native react-native-maps expo
当地图屏幕打开时,如何使地图居中以显示用户当前位置?按照expo文档,应该是用Expo Location API来实现吧?然而,文档并不清楚。我从世博会位置文档中获取了部分代码,并在我的地图屏幕中实现了它。那么,我应该如何将其集成到 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>
</>
);};
Run Code Online (Sandbox Code Playgroud)
小智 5
我也已经在这个问题上苦苦挣扎了几天,我发现很奇怪,即使 expo MapView 可以在地图上显示您自己的位置,但它无法返回您自己的 co\xc3\xb6rdinates。
\n尽管如此,该问题可以通过以下解决方案来解决。
\n\n\n展会安装展会位置
\n
import * as Location from \'expo-location\'\nRun Code Online (Sandbox Code Playgroud)\nconst [location, setLocation] = useState({});\nRun Code Online (Sandbox Code Playgroud)\nuseEffect(() => {\n (async () => {\n let { status } = await Location.requestForegroundPermissionsAsync();\n if (status !== \'granted\') {\n return;\n }\n\n let location = await Location.getCurrentPositionAsync({\n accuracy: Location.Accuracy.Balanced,\n enableHighAccuracy: true,\n timeInterval: 5\n });\n setLocation(location);\n })();\n }, []);\nRun Code Online (Sandbox Code Playgroud)\n<MapView ref={mapRef}>.... </MapView>\nRun Code Online (Sandbox Code Playgroud)\nconst mapRef = React.createRef();\nRun Code Online (Sandbox Code Playgroud)\nconst goToMyLocation = async () => {\n mapRef.current.animateCamera({center: {"latitude":location.coords.latitude, "longitude": location.coords.longitude}});\n}\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
3810 次 |
| 最近记录: |