【问题标题】:How to implement autodetect user location in react-native如何在 react-native 中实现自动检测用户位置
【发布时间】:2017-05-23 18:51:04
【问题描述】:

我正在尝试使用 geolocation API 在 react-native 中实现 自动检测用户位置 功能,但如果位置服务被禁用,它不会要求用户激活它就像在各种 Android 应用程序中一样,它要求用户使用谷歌位置服务激活它,然后获取用户的位置。

任何人都可以建议,我该如何实现这个功能。 ios和android有什么办法吗?

【问题讨论】:

    标签: react-native geolocation react-native-android react-native-ios google-location-services


    【解决方案1】:

    您可以在 iOS 和 Android 上使用react-native-permissions 轻松请求位置权限。

    【讨论】:

      【解决方案2】:

      如果您只需要自动检测地理位置,那么更好和最简单的方法是使用"navigator.geolocation"。您可以获取有关其用法的更多详细信息,以获取基于浏览器的 API 的位置 here

      您甚至不需要导入,因为它已经被您的浏览器继承了。您可以直接在类中使用:

      class className extends Component {
      
      
        state = {
          initialPosition: 'unknown',
          lastPosition: 'unknown',
       }
      
         watchID: ? number = null;
         componentDidMount = () => {
            navigator.geolocation.getCurrentPosition(
               (position) => {
                  const initialPosition = JSON.stringify(position);
                  this.setState({ initialPosition });
               },
               (error) => alert(error.message),
               { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 }
            );
            this.watchID = navigator.geolocation.watchPosition((position) => {
               const lastPosition = JSON.stringify(position);
               this.setState({ lastPosition });
            });
         }
         componentWillUnmount = () => {
            navigator.geolocation.clearWatch(this.watchID);
         }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-05
        • 1970-01-01
        • 2019-03-13
        • 2017-07-06
        • 2021-08-23
        相关资源
        最近更新 更多