我正在使用React Native构建一个基本的GPS应用程序,但我无法获取它来不断更新位置标记,我认为navigator.geolocation.watchPostion()函数应该可以做到这一点? (不要介意样式表不在代码中,它在那里) 据我所知,watchPostion仅被调用一次。
import React, { Component } from 'react';
import { Text, View, StyleSheet } from 'react-native';
import { Constants, MapView} from 'expo';
const LAT_DELTA = 0.00422;
const LONG_DELTA = 0.004021;
watchID = null
export default class App extends Component {
state = {
Position: {
latitude: 0,
longitude: 0,
latitudeDelta: LAT_DELTA,
longitudeDelta: LONG_DELTA
},
markerPos:{latitude: 26.274540, longitude:49.95531}
}
componentDidMount() {
this.watchID = navigator.geolocation.watchPosition( pos =>{
var lat = pos.coords.latitude;
var long = pos.coords.longitude;
var newState = {
latitude: lat,
longitude: long,
latitudeDelta: LAT_DELTA,
longitudeDelta: LONG_DELTA
}
this.setState({Position: newState})
this.setState({markerPos: newState})
}, error => console.log(error),
{
enableHighAccuracy: true,
timeout: 20000,
maximumAge: 1000,
distanceFilter: 10
})
}
componentWillUnmount = () => {
navigator.geolocation.clearWatch(this.watchID)
}
render() {
return (
<View style={styles.container}>
<MapView
style={{ alignSelf: 'stretch', height: 500 }}
region={this.state.Position}
mapType ={'satellite'}
>
<MapView.Marker
coordinate={this.state.Position}
title="My Marker"
description="Some description"
/>
</MapView>
<Text>
Location: {JSON.stringify(this.state.Position)}
</Text>
</View>
);
}
}