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        //時間戳 
}    

截圖如下:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM