gpt4 book ai didi

javascript - react native : Get position updates for every one second

转载 作者:行者123 更新时间:2023-11-30 09:30:03 24 4
gpt4 key购买 nike

目前,我有这个当前代码,它可以工作,但不是大多数时候。我有时会出现延迟,根本不更新。我的目标是获得实时位置更新。我的方法是使用 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);
}

最佳答案

我通过每 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',
},
});

关于javascript - react native : Get position updates for every one second,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46861642/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com