android - 在 React Native AirBnb 的 MapView [Android] 上关注用户位置

标签 android google-maps reactjs react-native geolocation

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

我的问题:

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

我注意到的:

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

我想要的:

  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}
    );
  }

最佳答案

我一直发现 watchPosition 在不同的浏览器之间存在问题,之前对我有用的一件事是在 setInterval 中用 getCurrentPosition 替换所以它会每隔几秒获取一次位置,如果失败,它将在下一个间隔重试,这与 watchPosition 不同,它会在发生错误时停止监视。

一般浏览器地理定位不是很可靠,你可以检查这个线程的一些问题https://github.com/facebook/react-native/issues/7495

另一种肯定会更快并且可能更可靠的替代方法是使用 native 地理定位 API。检查此问题,了解为 React Native 公开原生地理位置的库 React-native Android geolocation

关于android - 在 React Native AirBnb 的 MapView [Android] 上关注用户位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40929718/

相关文章:

java - Android ScheduledThreadPoolExecutor 立即执行延迟任务

javascript - Rails 的谷歌地图 : after map load callback

python - Google Maps API 未检索所有商店结果

java - android(api 8或更高)从位置获取地址

javascript - this.props.getItemCount 不是函数(VirtualizedList、React Native)

javascript - React.js onShow 事件处理程序

Android Spinner 使用 ArrayList 填充

android - 该代码不断告诉我我需要更新Google Play服务。我该如何解决?

wordpress - WordPress的古腾堡: React components on front end

android - RSS Feed 和 Google 的 XML 适配器示例 - 它有效吗?