float bearingBetweenLocations(LatLng latLng1, LatLng latLng2) {
double PI = 3.14159;
double lat1 = latLng1.getLatitude() * PI / 180;
double long1 = latLng1.getLongitude() * PI / 180;
double lat2 = latLng2.getLatitude() * PI / 180;
double long2 = latLng2.getLongitude() * PI / 180;
double dLon = (long2 - long1);
double y = Math.sin(dLon) * Math.cos(lat2);
double x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1)
* Math.cos(lat2) * Math.cos(dLon);
double brng = Math.atan2(y, x);
brng = Math.toDegrees(brng);
brng = (brng + 360) % 360;
return (float) brng;
}
如果您更喜欢使用库而不是您建议的方法,那么我建议使用Turf。 "Turf android"是由Mapbox团队创建的库,其中包含许多有用的方法,包括此方法。
/*
Takes two {@link Point}s and finds the geographic bearing between them.
*/
TurfMeasurement.bearing(@NonNull Point point1, @NonNull Point point2)
1- 首先需要输入 - 您需要从位置对象获取getBearing()。
2- 您需要正确的输出 - 有两种方法可以做到 -
a. 如果您使用png图标,则可以为每个10度创建一个箭头(36个箭头),并使用正确的图标更新标记,如果当前方位与旧方位不同。
b. 更好的选择,但我不知道这是否有效:Mapbox的标记具有options.rotation选项。但在Android中,Mapbx已移至Mapbox注释插件,请参见here
SymbolManager有一个名为setIconRotationAlignment的函数。因此,如果您可以使用这个类,我相信您可以通过方位角设置图标的旋转。
您还可以在此演示中看到其中一个选项是“将图标旋转至45度”。
3- 还有一件事 - 你可能也想获取getBearingAccuracyDegrees的输入,以了解当你没有足够准确的方位时,并向用户提供指示。