1,getCurrentPosition()方法介紹
static getCurrentPosition(geo_success, geo_error?, geo_options?
該方法用於獲取當前的位置,其參數如下:
(1)geo_success:成功回調函數
(2)geo_error:失敗回調函數
(3)geo_options:傳遞的參數。其支持的屬性有:
- timeout:指定獲取地理位置的超時時間,默認不限時。單位為毫秒。
- maximumAge:最長有效期,在重復獲取地理位置時,此參數指定多久再次獲取位置。默認為 0,表示瀏覽器需要立刻重新計算位置。
- enableHighAccuracy:指示瀏覽器獲取高精度的位置,默認為 false。當開啟后,可能沒有任何影響,也可能使瀏覽器花費更長的時間獲取更精確的位置數據。
樣例代碼,直接可以使用
import React from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; var Geolocation = require('Geolocation'); //默認應用的容器組件 export default class Localtion extends React.Component { static navigationOptions = ({ navigation }) => { const { navigate } = navigation; return { title: '獲取定位' }; }; //渲染 render() { return ( <View style={styles.container}> <Text style={styles.item} onPress={this.getLocation.bind(this)}>獲取位置</Text> </View> ); } //獲取位置 getLocation() { 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) } ); } } //樣式定義 const styles = StyleSheet.create({ container:{ flex: 1, marginTop:25 }, item:{ margin:15, height:30, borderWidth:1, padding:6, borderColor:'#ddd', textAlign:'center' }, });
二、監視定位變化
1,watchPosition()方法介紹
如果我們需要設定一個回調函數來不斷響應定位數據發生的變更(設備發生了移動,或獲取到了更高精度的地理位置信息)。可以通過 watchPosition() 函數實現該功能。
watchPosition() 與 getCurrentPosition() 接收的參數相同,但回調函數會被調用多次。
我們可以直接調用 watchPosition() 函數,不需要先調用 getCurrentPosition() 函數。2,clearWatch()方法介紹
根據傳入的 watchid 來對應的位置監聽活動。樣例代碼
-
import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; var Geolocation = require('Geolocation'); //監聽定位的id var watchID = null //默認應用的容器組件 class App extends Component { //渲染 render() { return ( <View style={styles.container}> <Text style={styles.item} onPress={this.beginWatch.bind(this)}>開始監聽</Text> <Text style={styles.item} onPress={this.stopWatch.bind(this)}>停止監聽</Text> </View> ); } //開始監聽位置變化 beginWatch() { 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) } ); } //停止監聽位置變化 stopWatch() { Geolocation.clearWatch(watchID); } } //樣式定義 const styles = StyleSheet.create({ container:{ flex: 1, marginTop:25 }, item:{ margin:15, height:30, borderWidth:1, padding:6, borderColor:'#ddd', textAlign:'center' }, }); AppRegistry.registerComponent('ReactDemo', () => App);