Arch1tect Arch1tect - 5 months ago 104
Android Question

How to center the camera so that marker is at the bottom of screen? (Google map api V2 Android)

When a marker is clicked, the default behavior for the camera is to center it on screen, but because I usually have long text description in the info window, it's more convenient to actually change the camera position so that the marker is on the bottom of screen(making the info window in the center of screen). I think I should be able to do that by overriding onMarkerClick function like below (the default behavior is cancelled when this function return true)

@Override

public boolean onMarkerClick(final Marker marker) {


// Google sample code comment : We return false to indicate that we have not

// consumed the event and that we wish
// for the default behavior to occur (which is for the camera to move
// such that the
// marker is centered and for the marker's info window to open, if it
// has one).

marker.showInfoWindow();

CameraUpdate center=
CameraUpdateFactory.newLatLng(new LatLng(XXXX,
XXXX));
mMap.moveCamera(center);//my question is how to get this center

// return false;
return true;
}


Edit:

Problem solved using accepted answer's steps, codes below:

@Override

public boolean onMarkerClick(final Marker marker) {

//get the map container height
LinearLayout mapContainer = (LinearLayout) findViewById(R.id.map_container);
container_height = mapContainer.getHeight();

Projection projection = mMap.getProjection();

LatLng markerLatLng = new LatLng(marker.getPosition().latitude,
marker.getPosition().longitude);
Point markerScreenPosition = projection.toScreenLocation(markerLatLng);
Point pointHalfScreenAbove = new Point(markerScreenPosition.x,
markerScreenPosition.y - (container_height / 2));

LatLng aboveMarkerLatLng = projection
.fromScreenLocation(pointHalfScreenAbove);

marker.showInfoWindow();
CameraUpdate center = CameraUpdateFactory.newLatLng(aboveMarkerLatLng);
mMap.moveCamera(center);
return true;



}


Thanks for helping ^ ^

Answer

I might edit this answer later to provide some code, but what I think could work is this:

  1. Get LatLng (LatLng M) of the clicked marker.
  2. Convert LatLng M to a Point (Point M) using the Projection.toScreenLocation(LatLng) method. This gives you the location of the marker on the device's display (in pixels).
  3. Compute the location of a point (New Point) that's above Point M by half of the map's height.
  4. Convert the New Point back to LatLng and center the map on it.

Look here for my answer on how to get the map's height.

Comments