我试图在我的本机应用程序上使用地理定位。 我已经开始遵循React Native Geolocation Tutorial但是没有运气。
import React, {Component} from 'react'
import {View, Text, TouchableOpacity} from 'react-native'
import {styles} from './locationPageStyles.js'
export default class LocationPage extends Component {
constructor(props) {
super(props)
this.state = {
initialPosition: 'unknownn',
lastPosition: 'unknown'
}
}
componentDidMount() {
navigator.geolocation.getCurrentPosition(
(position) => {
var initialPosition = JSON.stringify(position);
this.setState({initialPosition});
},
(error) => alert(error),
{enableHighAccuracy: true, timeout: 20000, maximumAge: 1000}
);
this.watchID = navigator.geolocation.watchPosition((position) => {
var lastPosition = JSON.stringify(position);
this.setState({lastPosition});
});
}
componentWillUnmount() {
navigator.geolocation.clearWatch(this.watchID);
}
render() {
return(
<View style={styles.container}>
<TouchableOpacity onPress={() => this.props.navigator.push({component: "startPage"})} >
<View style={{paddingVertical: 10, paddingHorizontal: 20, backgroundColor: 'yellow'}}>
<Text>Go to page ONE</Text>
</View>
</TouchableOpacity>
<View>
<Text>There is your geo {this.state.initialPosition} and {this.state.lastPosition}</Text>
</View>
</View>
)
}
}
一段时间后 - 发出“位置超时已结束”消息的警报。我试图增加timeOut,但没有结果。 (
GPS,位置,设备启用Wifi。 Permissios补充道。谷歌地图工作正常。哪里有问题?请帮助!
答案 0 :(得分:0)
我有同样的错误,它是由enableHighAccuracy引起的:true。不知道为什么,但有了它根本不起作用。
答案 1 :(得分:0)
使用此代码可能会对您有所帮助
- Don't forget to give location permission in manifest file
- <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
constructor(props){
super(props);
this.state = {
latitude: null,
longitude: null,
error: null,
};
}
componentDidMount(){
navigator.geolocation.getCurrentPosition( (position)=>{
//const ipos = JSON.stringify(Position);
this.setState({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
error: null,
});
},
(error) => this.setState({ error: error.message }),
{ enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 }
);
}