• ReactNative: 使用Geolocation的API获取位置信息


    一、简介

    LBS,基于位置的服务是很多APP必不可少的功能,根据获取的用户当前的位置,快速地提供给用户附近的资源【吃穿住行】。目前国内比较著名的地图服务提供商有百度地图、高德地图、以及腾讯地图等等。LBS最基础的功能就是位置的获取,ReactNative中提供了Geolocation这个API来进行定位,使用起来比较简单。使用react-native init创建的项目默认已经启动了这个服务。

    二、API

    Geolocation在ReactNative中已经进行了封装,当然用LBS这个服务之前,要获取用户的位置隐私必须得到权限允许,在Info.plis中配置NSLocationWhenInUseUsageDescription、NSLocationAlwaysUsageDescription、NSLocationAlwaysAndWhenInUseUsageDescription,Geolocation的常用的方法如下:

    //参数类型
    type GeoOptions = {
      timeout: number,               // 超时时长,单位为秒,若超时,触发失败回调函数
      maximumAge: number,            // 重复获取定位的间隔时长,单位为秒
      enableHighAccuracy: bool,      // 是否要求高精度的地理位置信息
      distanceFilter: number,        // 检索的范围,定义设备获得位置信息的最小距离 ,单位米
    }
    
    //获取当前的位置
    //参数geo_success为成功的回调函数,参数geo_error为失败的回调函数,参数geo_options是需要传递的参数,可选的。它的结构如上所示:
    getCurrentPosition: function(
        geo_success: Function,
        geo_error?: Function,
        geo_options?: GeoOptions
      ){ }
    
    
    //监测位置运动, 返回监测对象的ID:watchID
    watchPosition: function(success: Function, error?: Function, options?: GeoOptions): number {}
    
    //根据ID清除监测
    clearWatch: function(watchID: number){}
    
    //停止位置监听服务
    stopObserving: function(){}

    三、使用

    简单演示一下,代码和结果如下:

    /**
     * Sample React Native App
     * https://github.com/facebook/react-native
     * @flow
     */
    
    import React, { Component } from 'react';
    import {
        AppRegistry,
        StyleSheet,
        Text,
        TouchableHighlight,
        View
    } from 'react-native';
    
    const Geolocation = require('Geolocation');
    
    export default class App extends Component {
    
        //事件
        _event(){
    
            //参数配置
            const option = {
                timeout: 30,
                maximumAge: 10,
                enableHighAccuracy: true,
                distanceFilter: 100,
            };
    
            //获取位置
            Geolocation.getCurrentPosition((location)=>{
    
                console.log(JSON.stringify(location));
                alert("当前位置:"+JSON.stringify(location))
    
            }, (error) => {
    
                console.log(error);
                alert("获取位置失败: "+error);
    
            }, option)
        }
    
        render() {
            return (
                <View style={styles.container}>
                    <TouchableHighlight onPress={this._event.bind(this)}>
                        <Text style={{color:'red', fontSize:25}}>获取位置信息</Text>
                    </TouchableHighlight>
                </View>
            );
        }
    }
    
    const styles = StyleSheet.create({
        container: {
            flex: 1,
            justifyContent: 'center',
            alignItems: 'center',
            backgroundColor: '#F5FCFF',
        }
    });
    
    AppRegistry.registerComponent('App', () => App);

    日志如下:

    2020-01-15 16:35:48.054 [info][tid:com.facebook.react.JavaScript] {
        "coords":   
        {
            "speed":-1,  //速度
            "longitude":116.34597202677976,  //经度
            "latitude":39.97599651014569,    //纬度
            "accuracy":65,                   //位置精确度
            "heading":-1,                    //方向 
            "altitude":52.819034576416016,   //海拔高度 
            "altitudeAccuracy":10            //海拔精确度
        },
        "timestamp":1579077193398.279        //时间戳 
    }    

    截图如下:

     

  • 相关阅读:
    创业日记-时间过的也快也慢
    通过获取客户端Json数据字符串,反序列化为实体对象的一段代码
    Sandcastle是什么
    使用VisualSVN Server自动发布站点
    Microsoft Visual Studio Ultimate 2015 Preview使用笔记
    俞敏洪:自卑比狂妄更糟糕
    灰度发布
    TLV格式是什么格式
    zend studion实现自动换行
    数字格式化,从右往左每隔三位加逗号的四种方法
  • 原文地址:https://www.cnblogs.com/XYQ-208910/p/12197540.html
Copyright © 2020-2023  润新知