应用程序更新用户的位置,无论何时更新,我都希望它创建路径(折线),以便用户可以查看他们以前的路径。我怎么能做到这一点?每当调用onRegionChange
时,它都应该添加折线。
constructor(props) {
super(props);
this.state = {
latitude: null,
longitude: null,
error: null
};
}
componentDidMount() {
this.watchId = navigator.geolocation.watchPosition(
(position) => {
let region = {
latitude: position.coords.latitude,
longitude: position.coords.longitude,
latitudeDelta: 0.00922*1.5,
longitudeDelta: 0.00421*1.5
}
let coordinates = [
{latitude: position.coords.latitude, longitude: position.coords.longitude}
]
this.onRegionChange(region, region.latitude, region.longitude);
},
(error) => this.setState({ error: error.message }),
{ enableHighAccuracy: true, timeout: 20000, maximumAge: 1000, distanceFilter: 10 },
);
}
onRegionChange(region, lastLat, lastLong) {
this.setState({
mapRegion: region,
lastLat: lastLat || this.state.lastLat,
lastLong: lastLong || this.state.lastLong
});
}
componentWillUnmount() {
navigator.geolocation.clearWatch(this.watchId);
}
render() {
return (
<View style={styles.container}>
<MapView
style={styles.map}
region={this.state.mapRegion}
followUserLocation={true}
onRegionChange={this.onRegionChange.bind(this)}>
<MapView.Marker
coordinate={{
latitude: (this.state.lastLat) || -36.82339,
longitude: (this.state.lastLong) || -73.03569,
}}
title = {"You are here"}
description = {"Hi there!"}
/>
</MapView>
</View>
);
}
答案 0 :(得分:2)
我设法通过添加此代码来修复它
constructor(props) {
...
this.state = {
latitude: null,
longitude: null,
error: null,
routeCoordinates: []
};
}
componentDidMount() {
this.watchId = navigator.geolocation.watchPosition(
(position) => {
...
const { routeCoordinates } = this.state
const positionLatLngs = pick(position.coords, ['latitude', 'longitude'])
this.setState({ routeCoordinates: routeCoordinates.concat(positionLatLngs) })
...
}
...
render() {
return (
<View style={styles.container}>
<MapView
...
onRegionChange={this.onRegionChange.bind(this)}>
<MapView.Polyline
coordinates = {this.state.routeCoordinates}
strokeColor = '#19B5FE'
strokeWidth = {5}
/>
...
</MapView>
</View>
);
}