1:iOS xcode工程启用定位
在Info.plist
中增加NSLocationWhenInUseUsageDescription
字段来启用定位功能
2:android
需要在AndroidManifest.xml
文件中加入如下一行:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
3:Geolocation的方法
//获取当前地理位置
navigator.geolocation.getCurrentPosition(geo_success: Function, geo_error?: Function, geo_options?: GeoOptions)
//监听地理位置变化
watchID = navigator.geolocation.watchPosition(success: Function, error?: Function, options?: GeoOptions)
//清理监听
navigator.geolocation.clearWatch(watchID);
//停止监听
navigator.geolocation.stopObserving()
4:代码调用
import React, { Component } from 'react';
import {
AppRegistry,
View,
Text,
} from 'react-native';
class RNGeolocationView extends Component {
_watchID;
constructor(props) {
super(props);
this.state = {
text1: '',
text2: ''
}
}
componentDidMount() {
navigator.geolocation.getCurrentPosition(
(position) => {
let initialPosition = JSON.stringify(position);
this.setState({
text1: initialPosition
});
},
(error) => alert(error.message),
{enableHighAccuracy: true, timeout: 20000, maximumAge: 1000}
);
this._watchID = navigator.geolocation.watchPosition((position)=> {
let lastPosition = JSON.stringify(position);
this.setState({
text2: lastPosition
});
}, (error)=> {
alert(error.message)
})
}
componentWillUnmount() {
navigator.geolocation.clearWatch(this._watchID);
}
render() {
return (
<View style={{flex: 1, backgroundColor: '#ffaaff', alignItems: 'center', justifyContent: 'center'}}>
<Text>{this.state.text1}</Text>
<Text>{this.state.text2}</Text>
</View>
)
}
}
AppRegistry.registerComponent('RNGeolocationView', ()=>RNGeolocationView);
网友评论