【发布时间】:2018-05-28 09:35:33
【问题描述】:
我正在使用react-native 和react-native-maps 构建一个应用程序,该应用程序在用户当前位置显示一个标记,然后随着用户移动标记也随着用户在后面绘制路径而移动。
一切正常,但是当用户的位置发生变化时,标记移动似乎不是连续的,而是移动了更大的距离。
如下图所示,标记的移动不是连续的。有什么解决办法吗?
我正在关注这个tutorial
当前情景:
class AnimatedMarkers extends React.Component {
constructor(props) {
super(props);
this.state = {
latitude: LATITUDE,
longitude: LONGITUDE,
routeCoordinates: [],
distanceTravelled: 0,
prevLatLng: {},
coordinate: new AnimatedRegion({
latitude: LATITUDE,
longitude: LONGITUDE
})
};
}
componentWillMount() {
navigator.geolocation.getCurrentPosition(
position => {},
error => alert(error.message),
{
enableHighAccuracy: true,
timeout: 20000,
maximumAge: 1000
}
);
}
componentDidMount() {
this.watchID = navigator.geolocation.watchPosition(
position => {
const { coordinate, routeCoordinates, distanceTravelled } = this.state;
const { latitude, longitude } = position.coords;
const newCoordinate = {
latitude,
longitude
};
if (Platform.OS === "android") {
if (this.marker) {
this.marker._component.animateMarkerToCoordinate(
newCoordinate,
500
);
}
} else {
coordinate.timing(newCoordinate).start();
}
this.setState({
latitude,
longitude,
routeCoordinates: routeCoordinates.concat([newCoordinate]),
distanceTravelled:
distanceTravelled + this.calcDistance(newCoordinate),
prevLatLng: newCoordinate
});
},
error => console.log(error),
{ enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 }
);
}
calcDistance = newLatLng => {
const { prevLatLng } = this.state;
return haversine(prevLatLng, newLatLng) || 0;
};
getMapRegion = () => ({
latitude: this.state.latitude,
longitude: this.state.longitude,
latitudeDelta: LATITUDE_DELTA,
longitudeDelta: LONGITUDE_DELTA
});
render() {
return (
<View style={styles.container}>
<MapView
style={styles.map}
showUserLocation
followUserLocation
loadingEnabled
region={this.getMapRegion()}
>
<Polyline coordinates={this.state.routeCoordinates} strokeWidth={5} />
<Marker.Animated
ref={marker => {
this.marker = marker;
}}
coordinate={this.state.coordinate} />
</MapView>
<View style={styles.buttonContainer}>
<TouchableOpacity style={[styles.bubble, styles.button]}>
<Text style={styles.bottomBarContent}>
{parseFloat(this.state.distanceTravelled).toFixed(2)} km
</Text>
</TouchableOpacity>
</View>
</View>
);
}
}
【问题讨论】:
-
您无法连续获取位置,因为位置会根据设备定期更新。您可以使用时间戳保存最后的位置并插入移动。
-
使用样条线代替折线。
-
@ThomasSablik 哦,我知道你有参考链接可以帮助我吗?
-
有什么帮助?你想让我做什么?插值?
-
@ThomasSablik 是的,用当前位置插入最后一个位置?
标签: reactjs google-maps react-native react-native-maps