2016-09-15 70 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