2016-09-15 85 views
1

我正在使用mapbox sdk创建一个显示公交车位置的android应用程序。 我想像Uber应用那样根据位置旋转标记。 我怎么能做到这一点?MapBox中的标记方向android

代码:

IconFactory iconFactory = IconFactory.getInstance(navigationActivity.this); 
    Drawable iconDrawable = ContextCompat.getDrawable(navigationActivity.this, R.drawable.bus); 
    Icon icon = iconFactory.fromDrawable(iconDrawable); 
    map.clear(); 
    CameraPosition position = new CameraPosition.Builder() 
      .target(new LatLng(lat,lon)) // Sets the new camera position 
      .zoom(16) // Sets the zoom 
      .bearing(180) // Rotate the camera 
      .tilt(30) // Set the camera tilt 
      .build(); // Creates a CameraPosition from the builder 
    map.animateCamera(CameraUpdateFactory 
      .newCameraPosition(position), 7000); 
    final Marker marker = map.addMarker(new MarkerOptions() 
      .position(new LatLng(lat,lon)) 
      .title("You!") 
      .snippet("YOu are Currently here.")); 
    marker.setIcon(icon); 
+1

你没有提到你所面对的问题!你已经在代码 – Stallion

+2

中实现了轴承和倾斜功能。当地图加载时,它将生成动画并旋转。但是当另一个地点进入另一条水平线路时,公交车图标将沿着垂直方向进入该道路,标记的图像是..我需要它水平对齐@Stallion –

回答

3

这里的an example这确实你刚才问什么不同之处,而不是公交车,它跟踪国际空间站实时。标题的计算使用Turf和Mapbox Android Services SDK完成,但如果您只需要这种单一方法,则可以从库中复制该方法。下面是来自例子我上面提到的重要代码:

// Make sure you are using marker views so you can update the rotation. 
marker.setRotation((float) computeHeading(marker.getPosition(), position)); 

... 

public static double computeHeading(LatLng from, LatLng to) { 
// Compute bearing/heading using Turf and return the value. 
    return TurfMeasurement.bearing(
     Position.fromCoordinates(from.getLongitude(), from.getLatitude()), 
     Position.fromCoordinates(to.getLongitude(), to.getLatitude()) 
    ); 
} 

您也可以使用这个方法,我以前草坪以前用过:

// Returns the heading from one LatLng to another LatLng. Headings are. Expressed in degrees 
// clockwise from North within the range [-180,180). The math for this method came from 
// http://williams.best.vwh.net/avform.htm#Crs I only converted it to Java. 
public static double computeHeading(LatLng from, LatLng to) { 
    double fromLat = Math.toRadians(from.getLatitude()); 
    double fromLng = Math.toRadians(from.getLongitude()); 
    double toLat = Math.toRadians(to.getLatitude()); 
    double toLng = Math.toRadians(to.getLongitude()); 
    double dLng = toLng - fromLng; 
    double heading = Math.atan2(Math.sin(dLng) * Math.cos(toLat), 
      Math.cos(fromLat) * Math.sin(toLat) - Math.sin(fromLat) * Math.cos(toLat) * Math.cos(dLng)); 
    return (Math.toDegrees(heading) >= -180 && Math.toDegrees(heading) < 180) ? 
      Math.toDegrees(heading) : ((((Math.toDegrees(heading) + 180) % 360) + 360) % 360 + -180); 
} 
+2

我试过第二个功能仍然没有指向方向.. –

+2

嘿,我的错误,无论从和我给同样的cordinates ..现在它的工作..但我现在面临的另一个问题是每次当标记从标记改变它即使它在相同的方向旋转.. –

+0

它不应该,每一次旋转。上面的代码唯一的问题是它会始终顺时针旋转标记,即使逆时针旋转会更短。一个解决方案将是一个if检查,以确定旋转方向。 – cammace