如何定位地图,使两个标记在垂直线上对齐

时间:2014-12-16 21:15:08

标签: android google-maps bearing

我正在开发一个使用谷歌地图将用户导航到给定位置的应用程序。我想定位地图,使目标点始终位于地图的顶部,当前位置标记位于底部,两个标记在地图中垂直对齐并居中(例如,它们之间的垂直线是垂直的到屏幕)

我的方法是找到标记的中点,然后计算旋转地图的方位,使两个标记最终垂直对齐并居中。使中点居中将使标记居中,但我无法计算轴承的正确值。

任何帮助将不胜感激。

修改: 我试过了Location.bearingToLocation.distanceBetween。对于相同的输入,它们返回不同的值,从Location.distanceBetween返回的值是我正在寻找的。

EDIT2(代码示例)

public static void positionMap(GoogleMap map, LatLng start, LatLng end) {
    // zoom the map so both locations are visible
    LatLngBounds bounds = LatLngBounds.builder().include(start).include(end).build();
    map.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 200));

    // find the bearing
    float[] results = new float[3];
    Location.distanceBetween(
        start.latitude,
        start.longitude,
        end.latitude,
        end.longitude,
        results);
    float bearing = results[2];

    // position the map so the two markers are vertically aligned
    CameraPosition position = map.getCameraPosition();
    CameraPosition cameraPosition = new CameraPosition.Builder(position)
        .target(Utils.median(start, end))
        .bearing(bearing)
        .build();
    map.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}

2 个答案:

答案 0 :(得分:2)

查看位置对象的distanceBetween方法。

这是doc。初始轴承是您需要从起点使用的轴承,最终轴承是您到达目的地时将要使用的轴承。我想你会对初始轴承感兴趣。

public static void distanceBetween (double startLatitude, double startLongitude, double endLatitude, double endLongitude, float[] results)

Added in API level 1
Computes the approximate distance in meters between two locations, and optionally the initial and final bearings of the shortest path between them. Distance and bearing are defined using the WGS84 ellipsoid.

The computed distance is stored in results[0]. If results has length 2 or greater, the initial bearing is stored in results[1]. If results has length 3 or greater, the final bearing is stored in results[2].

Parameters
startLatitude   the starting latitude
startLongitude  the starting longitude
endLatitude the ending latitude
endLongitude    the ending longitude
results an array of floats to hold the results
Throws
IllegalArgumentException    if results is null or has length < 1

答案 1 :(得分:0)

您可以尝试使用Location.bearingTo()

不幸的是,这需要从LatLng转换为Location,但这应该很简单。