我一直在Android中使用Google地图服务。我想知道是否有一个实用方法,可以给出一个LatLng相对于另一个的方向。
我想知道一个点是在
南边还是北边
东边还是西边
- 或两者的组合
SomeUtil.direction(latlng1,latlng2) -> 例如,给我latlng2相对于latlng1的方向,如南西
先感谢您的帮助
我一直在Android中使用Google地图服务。我想知道是否有一个实用方法,可以给出一个LatLng相对于另一个的方向。
我想知道一个点是在
南边还是北边
东边还是西边
SomeUtil.direction(latlng1,latlng2) -> 例如,给我latlng2相对于latlng1的方向,如南西
先感谢您的帮助
NORTH、SOUTH、EAST、WEST以及NORTH-EAST等组合只是方向间隔的名称,你可以通过SphericalUtil
类中computeHeading()
方法获取(方向)值,该类属于Google Maps Android API Utility Library。
computeHeading
public static double computeHeading(LatLng from, LatLng to)
Returns the heading from one LatLng to another LatLng. Headings are expressed in degrees clockwise from North within the range [-180,180).
Returns: The heading in degrees clockwise from north.
然后通过将罗盘方位角度转换为方向名称(Δ,delta-确定方向的“基准”角度= 22.5度,因为360/8/2,其中^ 8是方向数量,如北、南等)来获得方向:
完整源代码:enum LocationDirection {
UNKNOWN,
NORTH,
NORTH_EAST,
EAST,
SOUTH_EAST,
SOUTH,
SOUTH_WEST,
WEST,
NORTH_WEST
}
public static LocationDirection direction(LatLng latlng1, LatLng latlng2) {
double delta = 22.5;
LocationDirection direction = LocationDirection.UNKNOWN;
double heading = SphericalUtil.computeHeading(latlng1, latlng2);
if ((heading >= 0 && heading < delta) || (heading < 0 && heading >= -delta)) {
direction = LocationDirection.NORTH;
} else if (heading >= delta && heading < 90 - delta) {
direction = LocationDirection.NORTH_EAST;
} else if (heading >= 90 - delta && heading < 90 + delta) {
direction = LocationDirection.EAST;
} else if (heading >= 90 + delta && heading < 180 - delta) {
direction = LocationDirection.SOUTH_EAST;
} else if (heading >= 180 - delta || heading <= -180 + delta) {
direction = LocationDirection.SOUTH;
} else if (heading >= -180 + delta && heading < -90 - delta) {
direction = LocationDirection.SOUTH_WEST;
} else if (heading >= -90 - delta && heading < -90 + delta) {
direction = LocationDirection.WEST;
} else if (heading >= -90 + delta && heading < -delta) {
direction = LocationDirection.NORTH_WEST;
}
return direction;
}
NB!您需要添加行
compile 'com.google.maps.android:android-maps-utils:0.5+'
SphericalUtil
类的依赖项添加到 build.gradle
文件的 dependencies
部分。computeOffset
方法(https://developers.google.com/maps/documentation/android-api/utility/):你有距离和所有的LatLng。你可以传递角度值并检查它们是否满足你的公式。public static LatLng computeOffset(LatLng from, double distance, double heading)
返回从指定起点向指定方向(相对于正北顺时针度数)移动指定距离后的 LatLng。
参数:
- distance - 要移动的距离。
- from - 起始 LatLng。
- heading - 相对于正北顺时针度数。
bearingTo()
方法来计算角度,而且从LatLng
转换到Location
应该很容易。但是也许Google Maps Android API Utility Library有你需要的东西。我并不确定,所以这只是一个注释而不是一个正式的答案。 - Markus Kauppinen