2011-10-10 138 views

回答

1

查看本教程。它應該讓你在正確的方向Compass Tutorial 也開始在這裏是個不錯的選擇Second Compass tutorial

+6

似乎並沒有這些例子回答這個問題。這些只創建一個指向北方的指南針,而不是自定義位置,不是? – rodi

1

您可以從here實現簡單的指南針。 它明顯指向北方,但爲了將指南針指向某個位置或座標,您可以做一些這樣的事情。

在您的活動中添加此方法,它找到兩個座標之間的方位。

protected double bearing(double startLat, double startLng, double endLat, double endLng){ 
     double longitude1 = startLng; 
     double longitude2 = endLng; 
     double latitude1 = Math.toRadians(startLat); 
     double latitude2 = Math.toRadians(endLat); 
     double longDiff= Math.toRadians(longitude2-longitude1); 
     double y= Math.sin(longDiff)*Math.cos(latitude2); 
     double x=Math.cos(latitude1)*Math.sin(latitude2)-Math.sin(latitude1)*Math.cos(latitude2)*Math.cos(longDiff); 

    return (Math.toDegrees(Math.atan2(y, x))+360)%360; 
} 

在北斗類onSensorChanged方法,做到這一點

azimuth -= bearing(yourlatitude, yourlongitude, latWhereToPoint, lngWhereToPoint); 

緯度,經度 - >您當前的緯度,經度 latWhereToPoint,lngWheretoPoint - >在那裏你想要點位置。

在最後你的onSensorChanged會是這樣的。

@Override 
public void onSensorChanged(SensorEvent event) { 
    final float alpha = 0.97f; 

    synchronized (this) { 
     if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { 

      mGravity[0] = alpha * mGravity[0] + (1 - alpha) 
        * event.values[0]; 
      mGravity[1] = alpha * mGravity[1] + (1 - alpha) 
        * event.values[1]; 
      mGravity[2] = alpha * mGravity[2] + (1 - alpha) 
        * event.values[2]; 

      // mGravity = event.values; 

      // Log.e(TAG, Float.toString(mGravity[0])); 
     } 

     if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) { 
      // mGeomagnetic = event.values; 

      mGeomagnetic[0] = alpha * mGeomagnetic[0] + (1 - alpha) 
        * event.values[0]; 
      mGeomagnetic[1] = alpha * mGeomagnetic[1] + (1 - alpha) 
        * event.values[1]; 
      mGeomagnetic[2] = alpha * mGeomagnetic[2] + (1 - alpha) 
        * event.values[2]; 
      // Log.e(TAG, Float.toString(event.values[0])); 

     } 

     float R[] = new float[9]; 
     float I[] = new float[9]; 
     boolean success = SensorManager.getRotationMatrix(R, I, mGravity, 
       mGeomagnetic); 
     if (success) { 
      float orientation[] = new float[3]; 
      SensorManager.getOrientation(R, orientation); 
      // Log.d(TAG, "azimuth (rad): " + azimuth); 
      azimuth = (float) Math.toDegrees(orientation[0]); // orientation 
      azimuth = (azimuth + 360) % 360; 

      azimuth -= bearing(yourlatitude, yourlongitude, latWhereToPoint, lngWhereToPoint); 
      // Log.d(TAG, "azimuth (deg): " + azimuth); 
      adjustArrow(); 
     } 
    } 
} 
相關問題