Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 751
Marcel Avatar asked Dec 09 '22 09:12

Marcel


1 Answers

I am not sure how much i am correct but i am just sharing my idea.

  1. Find the middle point(latitude longitude) of two marker

    private LatLng midPoint(double lat1, double long1, double lat2,double long2)
    {
    
    return new LatLng((lat1+lat2)/2, (long1+long2)/2);
    
    }
    
  2. Calculate angle between middle point and any other marker position.

    private double angleBteweenCoordinate(double lat1, double long1, double lat2,
        double long2) {
    
    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;
    brng = 360 - brng;
    
    return brng;
    }
    
  3. Rotate map to that angle.

    CameraPosition cameraPosition = new CameraPosition.Builder().target(midPoint(lat1, lng1, lat2, lng2)).zoom(14).bearing(angleBteweenCoordinate(lat1, lng1, lat2, lng2)).build();

    mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

like image 130
Md. Monsur Hossain Tonmoy Avatar answered Apr 25 '23 10:04

Md. Monsur Hossain Tonmoy