安卓 - 如何获取两个位置之间的方位角度?

6
如标题所述,我有当前位置,并想知道从我的当前位置到另一个位置的方位角度。我已阅读了这篇帖子,location.getBearing()返回的值是我的答案吗?
简单来说:从图片中看,我期望得到45度的值。

那个方法的文档告诉你什么?由于你没有说明为什么认为 getBearing() 不是正确的方法,所以这个问题无法回答。 - Simon
1
使用float bearing = myLocation.bearingTo(otherLocation);。 - NickT
4个回答

4

我遇到了困难,但最终通过将C?方法转换为计算方位角度的方法来解决了问题。

我使用了4个坐标点进行计算

起始纬度

起始经度

结束纬度

结束经度

以下是代码:

    protected double bearing(double startLat, double startLng, double endLat, double endLng){
    double latitude1 = Math.toRadians(startLat);
    double latitude2 = Math.toRadians(endLat);
    double longDiff= Math.toRadians(endLng - startLng);
    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;
}

只需在需要的地方更改变量名称。

将输出放入TextView中

希望这有所帮助!


1
我尝试了相同的方法,但是我得到了90度的偏移,我已经在起点和终点处给出了相同的位置,这应该给我0度,我还尝试了一个180度的位置,但结果相同。 - ateebahmed

3

定位类有一个方法叫做bearingTo: float bearingTo(Location dest)

Location from = new Location(LocationManager.GPS_PROVIDER);
Location to = new Location(LocationManager.GPS_PROVIDER);
from.setLatitude(0);
from.setLongitude(0);
to.setLongitude(10);
to.setLatitude(10);

float bearingTo = from.bearingTo(to);

该方法在相同位置上给我90度的偏移,并且在具有180度方位的位置上也是如此。 - ateebahmed

2

这是计算两点之间方位角的代码(起始点 startPoint,终止点 endPoint):

public float CalculateBearingAngle(double startLatitude,double startLongitude, double endLatitude, double endLongitude){
    double Phi1 = Math.toRadians(startLatitude);
    double Phi2 = Math.toRadians(endLatitude);
    double DeltaLambda = Math.toRadians(endLongitude - startLongitude);

    double Theta = atan2((sin(DeltaLambda)*cos(Phi2)) , (cos(Phi1)*sin(Phi2) - sin(Phi1)*cos(Phi2)*cos(DeltaLambda)));
    return (float)Math.toDegrees(Theta);
}

函数调用:

float angle = CalculateBearingAngle(startLatitude, startLongitude, endLatitude, endLongitude);

0
我发现了计算“两点方位角”的最佳方法,来自this answer,并将其从Python转换为Java。这个方法对我非常有效!
以下是代码:
    public static double getBearing(double startLat, double startLng, double endLat, double endLng) {

    double latitude1 = Math.toRadians(startLat);
    double longitude1 = Math.toRadians(-startLng);
    double latitude2 = Math.toRadians(endLat);
    double longitude2 = Math.toRadians(-endLng);

    double dLong = longitude2 - longitude1;

    double dPhi = Math.log(Math.tan(latitude2 / 2.0 + Math.PI / 4.0) / Math.tan(latitude1 / 2.0 + Math.PI / 4.0));
    if (abs(dLong) > Math.PI)
        if (dLong > 0.0)
            dLong = -(2.0 * Math.PI - dLong);
        else
            dLong = (2.0 * Math.PI + dLong);

   return  (Math.toDegrees(Math.atan2(dLong, dPhi)) + 360.0) % 360.0;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接