Search code examples
androidgoogle-mapscameragoogle-maps-markers

Google Maps v2 centering and turning camera position to fit two markers


I'm struggling how to make a move with the camera to fit my two markers and keep them on the same level. So this implies modify zoom to fit them and turn camera to fit the markers on the same line.

The next two pics will clarify my question:

Current stateDesired state

So, what I done so far is this:

public void centerIncidentRouteOnMap(List<LatLng> copiedPoints) {
        double minLat = Integer.MAX_VALUE;
        double maxLat = Integer.MIN_VALUE;
        double minLon = Integer.MAX_VALUE;
        double maxLon = Integer.MIN_VALUE;
        for (LatLng point : copiedPoints) {
            maxLat = Math.max(point.latitude, maxLat);
            minLat = Math.min(point.latitude, minLat);
            maxLon = Math.max(point.longitude, maxLon);
            minLon = Math.min(point.longitude, minLon);
        }
        final LatLngBounds bounds = new LatLngBounds.Builder().include(new LatLng(maxLat, maxLon)).include(new LatLng(minLat, minLon)).build();
        mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 120));
}

But this only make the two markers fit on the screen, so I need to know how to rotate the camera with the correct angle to get the last pic.

Can anyone help me on this?

Thanks!


Solution

  • In - almost - pseudo-code, try something like it:

    CameraPosition cameraPosition = new CameraPosition.Builder()
    .target(Your_target)      // Sets the center of the map
    .zoom(YourZoom)                   // Sets the zoom
    .bearing(Your_Angle)                // -90 = west, 90 = east
    .tilt(Some_Tilt)      
    
    map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
    

    To retrieve the angle:

    float xDiff = x2 - x1;
    float yDiff = y2 - y1;
    return Math.Atan2(yDiff, xDiff) * 180.0 / Math.PI;