【问题标题】:Follow user location on React Native AirBnb's MapView [Android]在 React Native AirBnb 的 MapView [Android] 上关注用户位置
【发布时间】:2017-04-17 05:12:50
【问题描述】:

我在我的应用程序上使用 airbnb's map 进行 react-native。这个问题是针对 android 应用的,因为我还没有绕过 iOS 应用。

我的问题:

navigator.geolocation 在模拟器上运行良好,但在真实设备上耗时太长,以至于在旧设备上有时会超时。

我注意到的:

如果 showsUserLocation 属性设置为 true,我可以在 getCurrentPosition 解析之前在地图上看到原生的“当前位置”标记。

我想要什么:

  1. 我希望我的区域始终以用户位置为中心。
  2. 我想要一种访问本地地理定位 api 的方法(应该是 更快?),或者有人告诉我我做错了什么。下边是 代码示例。
  3. 我希望即使在打开/关闭位置服务后仍能检测到用户的位置。这是showsUserLocation prop 的行为,但似乎一旦 watchPostion 出错,它就会完全停止。

这是我目前所拥有的,它非常简单:

  componentDidMount() {
    navigator.geolocation.getCurrentPosition(
      (position) => {
        console.log("getCurrentPosition Success");
        this.setState({
          region: {
            ...this.state.region,
            latitude: position.coords.latitude,
            longitude: position.coords.longitude,
          }
        });
        this.props.resetNotifications();
        this.watchPosition();
      },
      (error) => {
        this.props.displayError("Error dectecting your location");
        alert(JSON.stringify(error))
      },
      {enableHighAccuracy: true, timeout: 20000, maximumAge: 1000}
    );
  }

  watchPosition() {
    this.watchID = navigator.geolocation.watchPosition(
      (position) => {
        console.log("watchPosition Success");
        if(this.props.followUser){
          this.map.animateToRegion(this.newRegion(position.coords.latitude, position.coords.longitude));
        }
      },
      (error) => {
        this.props.displayError("Error dectecting your location");
      },
      {enableHighAccuracy: true, timeout: 20000, maximumAge: 1000}
    );
  }

【问题讨论】:

  • 您应该带着您的设备离开办公室或家中进行位置测试。在真实设备中必须是enableHighAccuracy: true。它对我来说很完美。
  • @pedropeixoto 我完全按照安装指南中的要求完成了所有操作,但 showsUserLocation 对我不起作用。你能帮帮我吗?

标签: android google-maps reactjs react-native geolocation


【解决方案1】:

我总是在不同的浏览器之间找到watchPosition iffy,以前对我有用的一件事是在setInterval 中替换为getCurrentPosition,这样它每隔几秒钟就会获取位置,如果它失败一次它会在下一个间隔重试,不像watchPosition 会在发生错误时停止观察。

一般浏览器地理位置不是很可靠,有些问题可以查看这个帖子https://github.com/facebook/react-native/issues/7495

另一个肯定会更快并且可能更可靠的替代方法是使用本地地理定位 API。检查此问题以获取暴露本机地理位置以响应本机 React-native Android geolocation

的库

【讨论】:

  • 您发送的链接有很多内容需要消化,但它肯定会让我继续前进。赏金即将结束,所以我将奖励给你。谢谢!
  • 谢谢。底线是使用本地地理定位插件以获得更高的可靠性。祝你好运
【解决方案2】:

不确定这是否能解决您的问题,但试试这个:

navigator.geolocation.getCurrentPosition(
  (position) => {
    console.log("getCurrentPosition Success");
    this.setState({
      region: {
        ...this.state.region,
        latitude: position.coords.latitude,
        longitude: position.coords.longitude,
      }
    }, () => {
      this.props.resetNotifications();
      this.watchPosition();
    });
  },

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-18
    • 1970-01-01
    • 1970-01-01
    • 2015-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-04
    相关资源
    最近更新 更多