React-native实现定位的功能

1、在React-native中实现定位的功能的几种方式。

(1).使用rn中的自带的Geolocation实现定位。
(2).用第三放库react-native-location实现定位。

2.用rn中自带的Geolocation实现定位的详细步骤:

(1).如果是android进行定位手下是需要权限的通过以下代码设置权限:

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

(2).直接通过navigator.geolocation来进行定位,示例代码如下:

getLocation(){
     navigator.geolocation.getCurrentPosition(
      (position) => {
        console.log('position----------------);
        console.log(position);
      },
      (error) => {console.log(error);},
      {enableHighAccuracy: true, timeout: 20000, maximumAge: 1000}
    );
 }

3.通过react-native-location库进行定位。

(1).下载库到本地

npm install  react-native-location

(2).自动配置library
react-native link react-native-location
(3).如果是android系统需要权限

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

(4).示例

import RNLocation from 'react-native-location';

RNLocation.configure({
  distanceFilter: 5.0
})

RNLocation.requestPermission({
  ios: "whenInUse",
  android: {
    detail: "coarse"
  }
}).then(granted => {
    if (granted) {
      this.locationSubscription = RNLocation.subscribeToLocationUpdates(locations => {
        /* Example location returned
        {
          speed: -1,
          longitude: -0.1337,
          latitude: 51.50998,
          accuracy: 5,
          heading: -1,
          altitude: 0,
          altitudeAccuracy: -1
          floor: 0
          timestamp: 1446007304457.029
        }
        */
      })
    }
  })

猜你喜欢

转载自blog.csdn.net/weixin_42600398/article/details/95373057