【发布时间】:2018-07-18 17:55:58
【问题描述】:
我正在制作一个反应本机应用程序,我在其中显示公交车的实时位置。我正在使用 react-native-maps。标记和实时位置工作正常,但我找不到可以显示公共汽车方向的标记。
方向是指公共汽车的旋转,无论它向左、向右等。 像这样:
如何显示这样的标记?
【问题讨论】:
标签: javascript react-native expo react-native-maps
我正在制作一个反应本机应用程序,我在其中显示公交车的实时位置。我正在使用 react-native-maps。标记和实时位置工作正常,但我找不到可以显示公共汽车方向的标记。
方向是指公共汽车的旋转,无论它向左、向右等。 像这样:
如何显示这样的标记?
【问题讨论】:
标签: javascript react-native expo react-native-maps
您可以使用heading angle 来实现此目的,您从公共汽车到达的方向应该有一个航向值。
例如,你得到一个位置对象:
{ lat: 123, lng: 123, heading: 350 }
首先确保您接收到来自该位置的航向角。如果是这样,那么您需要使用Animated marker 来实现此目的。
例如:
在你的MapView
<MapView.Marker.Animated
coordinate={{ latitude: Number(origin.lat), longitude: Number(origin.lng) }}
ref={marker => { this.marker = marker }}
flat
style={{ transform: [{
rotate: origin.heading === undefined ? '0deg' : `${origin.heading}deg`
}]
}}
>
<Image
style={{
height: 25,
width: 25,
transform: [{
rotate: '270deg'
}]
}}
source={require('../../assets/car.png')}
/>
</MapView.Marker.Animated>
这里,origin.lat 和origin.lng 代表纬度和经度,如果您接收它们作为字符串,您可以将它们解析为Number,并且标题是指汽车的方向,并且图像是关闭的- 当然你的汽车标志和图像中的旋转只是为了稍微调整一下(这并不重要)。
现在你已经完成了 50%,
现在让我们看看componentWillReceiveProps 函数,
在这里,您需要根据标题更新方向。
componentWillReceiveProps(nextProps) {
const duration = 1000;
if (this.props.liveLocation.origin !== nextProps.liveLocation.origin) {
const newCoordinate = {
latitude: Number(nextProps.liveLocation.origin.lat),
longitude: Number(nextProps.liveLocation.origin.lng)
};
if (Platform.OS === 'android') {
if (this.marker) {
this.marker._component.animateMarkerToCoordinate(
newCoordinate,
duration
);
}
} else if (this.props.liveLocation.origin != null) {
const oldCoordinate = new AnimatedRegion({
latitude: Number(this.props.liveLocation.origin.lat),
longitude: Number(this.props.liveLocation.origin.lng)
});
oldCoordinate.timing(newCoordinate).start();
}
}
}
对于 ios,它并不完美,
flat 道具在您旋转地图时不会让标记内的图像旋转,但不幸的是它不适用于 ios,
您可以为 IOS 禁用地图旋转。
您也可以访问此处获取更多参考资料。 https://github.com/react-community/react-native-maps/issues/1701
【讨论】: