React Native - 使用Geolocation进行定位(获取当前位置、监听位置变化)

React Native 提供了 Geolocation API,让我们可以很方便的获取当前的位置信息,或者监听位置的变化。下面通过样例演示如何使用。
导入 API

var Geolocation = require('Geolocation');

一、获取当前的定位信息
1.getCurrentPosition()方法介绍

static getCurrentPosition(geo_success, geo_error?, geo_options?)
该方法用于获取当前的位置,其参数如下:
(1)geo_success:成功回调函数
(2)geo_error:失败回调函数
(3)geo_options:传递的参数。其支持的属性有:
timeout:指定获取地理位置的超时时间,默认不限时。单位为毫秒。
maximumAge:最长有效期,在重复获取地理位置时,此参数指定多久再次获取位置。默认为 0,表示浏览器需要立刻重新计算位置。
enableHighAccuracy:指示浏览器获取高精度的位置,默认为 false。当开启后,可能没有任何影响,也可能使浏览器花费更长的时间获取更精确的位置数据。

代码

//定位函数
  onPressLocition(){
    //获取经纬度
    Geolocation.getCurrentPosition(
     
      location => {
        var result = "速度:" + location.coords.speed +
                    "\n经度:" + location.coords.longitude +
                    "\n纬度:" + location.coords.latitude +
                    "\n准确度:" + location.coords.accuracy +
                    "\n行进方向:" + location.coords.heading +
                    "\n海拔:" + location.coords.altitude +
                    "\n海拔准确度:" + location.coords.altitudeAccuracy +
                    "\n时间戳:" + location.timestamp;
       alert(result);
    },
    error => {
     alert("获取位置失败:"+ error)
    }


  // );

//监听经纬度变化
// watchID = Geolocation.watchPosition(
//   location => {
//       var result = "速度:" + location.coords.speed +
//                   "\n经度:" + location.coords.longitude +
//                   "\n纬度:" + location.coords.latitude +
//                   "\n准确度:" + location.coords.accuracy +
//                   "\n行进方向:" + location.coords.heading +
//                   "\n海拔:" + location.coords.altitude +
//                   "\n海拔准确度:" + location.coords.altitudeAccuracy +
//                   "\n时间戳:" + location.timestamp;
//       alert(result);
//   },
//   error => {
//     alert("获取位置失败:"+ error)
//   }
// );



//停止监听位置变化
//Geolocation.clearWatch(watchID);


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值