目前,我有这个当前的代码,但是不是大部分时间。我有时会得到延迟,根本不会更新。我的目标是获得实时位置更新。我这样做的方法是使用setInterval()
函数,我在componentDidMount()
内部使用。
我试过navigator.geolocation.watchPosition
但是没有用。也许我以错误的方式使用它。
componentDidMount() {
this.state.interval = setInterval(() => {
navigator.geolocation.getCurrentPosition(
(position) => {
console.log("Pos: "+position.coords.speed);
this.setState({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
speed: position.coords.speed,
error: null,
});
},
(error) => this.setState({ error: error.message }),
{ enableHighAccuracy: true, maximumAge: 0},
);
},1000);
}
答案 0 :(得分:2)
我通过每隔x秒更新一次状态来解决它:
import { Platform, View, StyleSheet, Text } from 'react-native';
import Constants from 'expo-constants';
import * as Location from 'expo-location';
import * as Permissions from 'expo-permissions';
export default class App extends Component {
state = {
location: null,
errorMessage: null,
};
_getLocationAsync = async () => {
let { status } = await Permissions.askAsync(Permissions.LOCATION);
if (status !== 'granted') {
this.setState({
errorMessage: 'Permission to access location was denied',
});
}
let location = await Location.getCurrentPositionAsync({});
this.setState({ location });
};
componentDidMount() {
if (Platform.OS === 'android' && !Constants.isDevice) {
this.setState({
errorMessage: 'Oops, this will not work on Sketch in an Android emulator. Try it on your device!',
});
} else {
setInterval(this._getLocationAsync.bind(this),2000);
}
}
render () {
let text = 'Waiting..';
if (this.state.errorMessage) {
text = this.state.errorMessage;
} else if (this.state.location) {
text = JSON.stringify(this.state.location);
}
return (
<View style={styles.container}>
<Text style={styles.paragraph}>{text}</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
},
paragraph: {
margin: 24,
fontSize: 18,
textAlign: 'center',
},
});