【问题标题】:React Native Android GeoLocationReact Native Android 地理位置
【发布时间】:2016-05-05 15:33:57
【问题描述】:

我正在尝试在 Android React Native 应用程序中获取用户的位置。我从关注React Native Geolocation Tutorial 开始,但没有任何运气。

我已经为 Android 项目添加了相应的权限,并在 react native 应用中插入了这段代码:

  componentDidMount() {

    navigator.geolocation.getCurrentPosition(
      (position) => {
        var initialPosition = JSON.stringify(position);
        this.setState({initialPosition});
      },
      (error) => alert(error.message),
      {enableHighAccuracy: true, timeout: 20000, maximumAge: 1000}
    );
    console.log("Initial position: " + this.state.initialPosition)

  }

我也将initialPosition 变量定义为“未知”,就像在教程中一样。当示例运行时,initialPosition 变量打印未知。然后大约 5 秒后,警报显示“未定义”错误。

我对发生的事情有点困惑,因为错误为空。也许我错误地实例化了“地理位置”?不幸的是,我无法通过搜索找到很多关于此的信息,因此感谢您提供任何帮助。

【问题讨论】:

    标签: android geolocation react-native


    【解决方案1】:

    希望这能有所帮助:

    1. 您正在回调外部记录initialPosition。这意味着 initialPosition 将是未知的,因为回调尚未运行,因此 initialPosition 变量尚未更新。
    2. 尝试记录error 变量,而不仅仅是发出error.message 的警报。有可能存在error,但没有error.message

    【讨论】:

    • 感谢您的提示。打印错误返回“没有可用的位置提供程序”,所以至少现在我有一个方向。不知道为什么这没有存储在消息中..
    • 你试过了吗,没有 enableHighAccuracy: true。 IE: enableHighAccuracy: false?
    • 原来我没有在设备上启用位置。绝对不是我最好的时间之一......将来肯定需要抓住那个案子!
    【解决方案2】:
    1. 试试这段代码,它可能会对你有所帮助,并将 this.state 内的构造函数中的纬度和经度变量定义为 null。
    2. 如果要打印 json 字符串,则在 state 中定义一个数组,然后通过设置 this.setState 数组来使用
     - Don't forget to give location permission in manifest file
    

    -<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    componentDidMount(){
        navigator.geolocation.getCurrentPosition( (position)=>{
            //const ipos = JSON.stringify(Position);
            this.setState({
                latitude: position.coords.latitude,
                longitude: position.coords.longitude,
              });
        },
        { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 }
      );
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-25
      • 2023-03-20
      • 2015-11-28
      • 1970-01-01
      • 1970-01-01
      • 2020-08-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多