LatLng 相对于另一个 LatLng 的方向

ikb*_*bal 4 android google-maps

我一直在研究 Android 中的 Google 地图服务。我想知道是否有一种实用方法可以给出LatLng相对于另一个的方向。

我想知道一个点是否在

  • 南或北

  • 东或西

  • 或两个的组合,每个一个

SomeUtil.direction(latlng1,latlng2) -> 给我 latlng2 相对于 latlng1 的方向,例如西南

提前致谢

And*_*nko 5

NORTH、SOUTH、EAST、WEST 及其组合,如 NORTH-EAST 只是航向间隔的名称,您可以从Google Maps Android API Utility Library 中computeHeading()SphericalUtil类方法中获取(航向):

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.
Run Code Online (Sandbox Code Playgroud)

然后通过将航向罗盘度数转换为方向名称来获取方向(?, 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;
}
Run Code Online (Sandbox Code Playgroud)

注意!您需要添加行

compile 'com.google.maps.android:android-maps-utils:0.5+'
Run Code Online (Sandbox Code Playgroud)

到类使用dependenciesbuild.gradle文件部分SphericalUtil