问题描述
我正在尝试使用react-native-maps
获取当前位置。这是我的以下代码:
import MapView from 'react-native-maps';
import Geolocation from '@react-native-community/geolocation';
const [position,setPosition] = useState({
latitude: 10,longitude: 10,latitudeDelta: 0.001,longitudeDelta: 0.001,});
useEffect(() => {
Geolocation.getCurrentPosition(success,error,options);
},[]);
var options = {
enableHighAccuracy: true,timeout: 5000,maximumAge: 0,};
function success(pos) {
var crd = pos.coords;
setPosition({
latitude: crd.latitude,longitude: crd.longitude,latitudeDelta: 0.0421,longitudeDelta: 0.0421,});
}
function error(err) {
console.warn(`ERROR(${err.code}): ${err.message}`);
}
return (
<MapView
style={styles.map}
initialRegion={position}
showsUserLocation={true}
>
</MapView>
现在,如果我删除属性initialRegion
,则地图运行正常。但是使用上面的代码,我得到的是白屏,没有任何错误。
任何帮助将不胜感激。
解决方法
我认为您的代码存在问题,就是getCurrentPosition
失败了,并且由于position
内部的初始坐标已被放大,因此似乎没有显示任何内容。
还要确保启用了Google Maps API并react-native-maps is configured correctly。
这是我的工作方式:
import React,{useState,useEffect} from 'react';
import {StyleSheet} from 'react-native';
import MapView from 'react-native-maps';
import Geolocation from '@react-native-community/geolocation';
const App = () => {
const [position,setPosition] = useState({
latitude: 10,longitude: 10,latitudeDelta: 0.001,longitudeDelta: 0.001,});
useEffect(() => {
Geolocation.getCurrentPosition((pos) => {
const crd = pos.coords;
setPosition({
latitude: crd.latitude,longitude: crd.longitude,latitudeDelta: 0.0421,longitudeDelta: 0.0421,});
}).catch((err) => {
console.log(err);
});
},[]);
return (
<MapView
style={styles.map}
initialRegion={position}
showsUserLocation={true}
/>
);
};
const styles = StyleSheet.create({
map: {
...StyleSheet.absoluteFillObject,},});
export default App;