Sunday, January 3, 2010

Getting Relative Coordinates from MotionEvent

Category: UI
Subcategory: Window/View Coordinates (X, Y)
Android Platform: 1.5, Google APIs 3
Referenced Classes: android.app.Activity, android.view.GestureDetector, android.view.GestureDetector.SimpleOnGestureListener, android.view.MotionEvent, android.view.View, android.view.Window, com.google.android.maps.GeoPoint, com.google.android.maps.MapView
Additional Info: Vertical Orientation

I wanted to place OverlayItems where long-press MotionEvents occurred. In order to determine the position of an OverlayItem, I needed to get the relative X and Y coordinates of the corresponding MotionEvent. As mentioned in the following forum (http://stackoverflow.com/questions/1410885/how-do-i-know-if-a-motionevent-is-relative-or-absolute), I was unable to obtain the relative X and Y coordinates using the methods MotionEvent.getX() and MotionEvent.getY(), respectively. Given that my MapView filled the entire screen, I came up with the following method:
code snippet
public static float[] getRelativeCoords(Activity activity,
MotionEvent e)
{
// MapView
View contentView= activity.getWindow().
findViewById(Window.ID_ANDROID_CONTENT);
return new float[] {
e.getRawX() - contentView.getLeft(),
e.getRawY() - contentView.getTop()};
}
Using GestureDetector and GestureDetector.SimpleOnGestureListener, and calling the above getRelativeCoords(...), I was able to place an OverlayItem where every long-press MotionEvent occurred:
code snippet
final MapView mapView= ...
final Activity mapViewActivity= this;

new GestureDetector(mapViewActivity,
new SimpleOnGestureListener()
{
public void onLongPress(MotionEvent e)
{
float[] coords= getRelativeCoords(mapViewActivity, e);
GeoPoint point= mapView.getProjection().fromPixels(
(int) coords[0],
(int) coords[1]);
// create OverlayItem with point
...
...
}
});

1 comment:

  1. i would like to get a copy of ur project if it is open

    ReplyDelete