react-native-maps中的当前位置

问题描述

我正在尝试使用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,则地图运行正常。但是使用上面的代码,我得到的是白屏,没有任何错误

enter image description here

任何帮助将不胜感激。

解决方法

我认为您的代码存在问题,就是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;

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...