首页 > 解决方案 > 如何使用本机反应每 x 秒监控或更新用户位置?

问题描述

如何使用本机反应每 x 秒监控或更新用户位置?

我的代码:

export default class app extends React.Component {  
        constructor(props){  
            super(props);  
            this.state = {  
                ready: false,  
                where: {lat:null, lng:null},  
                error: null,
                time: String(new Date()),
            };
        }
        componentDidMount(){  
            let geoOptions = {  
                enableHighAccuracy:false,  
                timeOut: 20000,
            };  
            this.setState({ready:false, error: null });  
            Geolocation.getCurrentPosition( this.geoSuccess,  
                this.geoFailure,  
                geoOptions);  
            setInterval(() => {
                Geolocation.getCurrentPosition( this.geoSuccess,  
                    this.geoFailure,  
                    geoOptions);  
                    this.setState((oldState) => {     
                    return { 
                       time: String(new Date())
                    };
                   });
                   }, 1000);    
        }  
        geoSuccess = (position) => {  
            console.log(position.coords.latitude);  
      
            this.setState({  
                ready:true,  
                where: {lat: position.coords.latitude,lng:position.coords.longitude }  
            })
    
        }  
        geoFailure = (err) => {  
            this.setState({error: err.message});  
        }  
        
        render() { 
         
            return (  
                <View style={styles.container}>  
                    { !this.state.ready && (  
                        <Text style={styles.big}>Using Geolocation in React Native.</Text>  
                    )}  
                    { this.state.error && (  
                        <Text style={styles.big}>Error: {this.state.error}</Text>  
                    )}  
                    { this.state.ready && (  
                        <Text style={styles.big}>  
                            Latitude: {this.state.where.lat}{'\n'}{'\n'}
                            Longitude: {this.state.where.lng} {'\n'}{'\n'} 
                            {this.state.time}
                        </Text>  
                    )}  
                </View>  
            );  
        }  
    }

我使用 setInterval 每 1 秒获取一次用户的位置更新。

当它第一次获得位置时,再次,每当它检测到新位置时

但最后不知道该怎么做???非常感谢

标签: react-nativegeolocationsetinterval

解决方案


推荐阅读