react native定位时请求开启位置权限

react native 在使用 Geolocation 定位获取经纬度的时候w,如果用户不开启位置信息,不打开gps,则会报错,所以一开始应该判断用户有没有开启位置信息,如果没有的话请求用户打开位置信息
我在android react-native-android-location-services-dialog-box这个组件
React Native Android Location Services Dialog Box
https://github.com/webyonet/react-native-android-location-services-dialog-box

配置:
1.yarn add react-native-android-location-services-dialog-box

2.react-native link react-native-android-location-services-dialog-box

3.android/settings.gradle

include ':react-native-android-location-services-dialog-box'
project(':react-native-android-location-services-dialog-box').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-android-location-services-dialog-box/android')

4.android/app/build.gradle

dependencies {
   ...
   compile project(':react-native-android-location-services-dialog-box')
}

项目中使用

import LocationServicesDialogBox from "react-native-android-location-services-dialog-box"

如果要获取经纬度的话还需要引入Geolocation

import Geolocation from 'Geolocation'
 componentDidMount() {
        this.getLocation()
    }
  getLocation(){
          LocationServicesDialogBox.checkLocationServicesIsEnabled({
            message: "<h2>开启位置服务</h2>开启位置服务,获取精准定位<br/><a href='#'>了解更多</a>",
            ok: "去开启",
            cancel: "取消",
            enableHighAccuracy: true, 
            showDialog: true, 
            openLocationServices: true, 
            preventOutSideTouch: false, 
            preventBackClick: false, 
            providerListener: true 
        }).then(function(success) {
         
                Geolocation.getCurrentPosition((location) => {
                    let coordinate = [location.coords.longitude,location.coords.latitude]
                    this.props.saveLocation(coordinate);
                    this.setState({
                        currentLocation:coordinate
                    })
              });
            }.bind(this)
        ).catch((error) => {
            console.log(error.message);
        });
        DeviceEventEmitter.addListener('locationProviderStatusChange', function(status) { 
            console.log(status); 
        });
     }
 componentWillUnmount() {
        LocationServicesDialogBox.stopListener(); 
   } 

在这里插入图片描述

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值