【问题标题】:To get Current Location Automatically in Reactnative在 React Native 中自动获取当前位置
【发布时间】:2019-03-13 20:39:27
【问题描述】:

我有这种方法可以通过单击按钮来获取当前位置,它将获取当前位置。我想在不点击该按钮的情况下获取位置。

getLocationHandler = () =>{
   navigator.geolocation.getCurrentPosition(pos =>{

    const coordsEvent ={ 
      nativeEvent :{
        coordinate : {
          latitude : pos.coords.latitude,
          longitude : pos.coords.longitude
        }
      }
    };
this.pickLocationHandler(coordsEvent);

   },
   err => {
     console.log(err);
     alert("Fetching the position failed,Please pick one manually")
   })
 }

【问题讨论】:

  • 您想定期获取位置吗?在特定事件之后?
  • 我想在地图屏幕打开时显示当前位置

标签: react-native react-native-android react-native-maps


【解决方案1】:

您需要将位置保持在状态,并在安装组件时请求它。 使用react-native-maps,获取位置是一项异步任务,因此您需要这样的解决方案:

constructor(props){
    super(props);
    state = {
        myLocation: null
    };
}

componentDidMount = () => {
    this.getMyLocation();
};

getMyLocation = async () => {
    let { status } = await Permissions.askAsync(Permissions.LOCATION);
    if (status !== 'granted') {
        this.setState({
            myLocation: 'Permission denied',
        });
    }
    let location = await Location.getCurrentPositionAsync({});
    this.setState({
        myLocation: JSON.stringify(location)
    });
};

噢噢噢噢,你本来可以用谷歌搜索的

react-native-maps 获取当前位置

发现了这个github问题:https://github.com/react-community/react-native-maps/issues/1183

顺便感谢 github 问题的答案。干杯 Vivekburada !

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-10
    • 2018-05-13
    • 1970-01-01
    • 1970-01-01
    • 2019-04-12
    相关资源
    最近更新 更多