根据用户的方向生成标记

问题描述 投票:0回答:2

我正在制作一个反应本机应用程序,在其中显示公交车的实时位置。我正在使用反应本机地图。标记和实时位置工作正常,但我无法找到也可以显示公交车方向的标记。

方向是指公交车的旋转方向,无论是左转、右转等。 像这样:

如何显示这样的标记?

javascript react-native expo react-native-maps
2个回答
3
投票

您可以通过

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


0
投票

此外,如果您需要自定义标记的当前航向/坐标/速度或将相机视图航向更改为用户方向,您可以使用 onUserLocationChange

<MapView
   onUserLocationChange={(event) => {
     // event?.nativeEvent?.coordinate contains heading, lat, long, speed etc.

     const location = { coords: { ...event?.nativeEvent?.coordinate } };
     this._locationUpdatedHandler(location);
   }}
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.