Android Tutorial 2: “Hit” testing on a View (MapView)

The following tutorial addresses how to perform ‘hit’ testing for user ‘clicks’ in a View. By hit testing, we mean the ability to determine when a user’s selection of a specific Point in a View overlaps with a region that we are monitoring for further action.

In other words at the end of this MapView tutorial, your users will be able to click on any icon that you draw onto the map, and you’ll be able to take whatever action you like such as displaying a transparent popup window (as we do in the tutorial).

Here’s what the final result will look like:

Screenshot of Tutorial 2 results

We’ll assume you already know how to add a MapView to a layout and create an Overlay and will jump right into how to test whether a user selection ‘hit’ one of those mapped icons.

Our icons are rendered by an extension of Overlay we have named MapLocationOverlay which has 2 primary methods called during an Overlay.draw(). We’ll go through each of these in detail:

drawMapLocations(canvas, mapView, shadow);
drawInfoWindow(canvas,
mapView, shadow);

More important perhaps, we’ll discuss the following method which performs the hit testing of each user tap on the screen.

isHitMapLocation(mapView,point);

Starting with locations on our MapView

We start by creating a class, MapLocation, to store our map location name, latitude, & longitude. Four instances of MapLocation are created as shown in the screenshot of San Francisco above:

mapLocations = new ArrayList<MapLocation>();
mapLocations.add(new MapLocation(”North Beach”,37.799800872802734,-122.40699768066406));
mapLocations.add(new MapLocation(”China Town”,37.792598724365234,-122.40599822998047));
mapLocations.add(new MapLocation(”Fisherman’s Wharf”,37.8091011047,-122.416000366));
mapLocations.add(new MapLocation(”Financial District”,37.79410171508789,-122.4010009765625));

These map locations will be drawn to the MapView and used for testing user clicks.

Drawing Map Locations

Before we can test for users clicking our icon, we need to first learn how those icons are drawn to the screen. Once you are comfortable setting the screen coordinates for drawing of your icon, it will be simple to test those same coordinates for ‘hits’ (user clicks” on that icon).

Screen coordinates start at (0,0) in the upper-left and end at the bottom-right (screenWidth,screenHeight) of our screen. To draw our location’s icon, we must first know how to translate from the latitude/longitude coordinates of our map location to these x & y screen coordinates. Android provides this function for us via the Projection class which is available from the MapView passed in Overlay’s draw() method: MapView.getProjection()

public void draw(Canvas canvas, MapView mapView, boolean shadow)

To use Projection, simply pass an int[2] to Projection along with our location’s latitude/longitude as a Point. The projection does its magic and returns the screen coordinates of our map location.

int[] screenCoords = new int[2];
mapView.getProjection().getPointXY(testLocation.getPoint(), screenCoords);

As we will be drawing a bitmap balloon icon to the screen, we must ensuring that the bottom middle of our icon is directly on top of our location’s latitude & longitude screen coordinates (as shown in the image below). This accurate positioning of our icon will be key to hit testing later on.

Screen coordinates of icon

To draw the balloon icon then, we call drawBitmap() and ensure the top/left of our icon is properly offset.

canvas.drawBitmap(icon, screenCoords[0] – icon.width()/2, screenCoords[1] – icon.height(),null);

And that’s it, our icons is now properly drawn on the screen. Now we need to perform ‘hit’ tests for user interaction with these icons.

Listening for Map Taps & Then Testing for ‘Hits’

User taps on the MapView are captured by overriding Overlay’s onTouchEvent() method and then testing for overlap with our icons’ locations on the screen. If a hit occurs and new information popup displayed (or a prior information popup removed), then we invalidate the map so Overlay.draw() is called.

@Override
public boolean onTouchEvent(MotionEvent event, MapView mapView) {

// Store whether prior popup was displayed so call invalidate() to remove it if necessary.
boolean isRemovePriorPopup = selectedMapLocation != null;

// Next test whether a new popup should be displayed
selectedMapLocation = getHitMapLocation(mapView,event);
if ( isRemovePriorPopup || selectedMapLocation != null) {

mapView.invalidate();

}

// Lastly return true if we handled this onTap()
return selectedMapLocation != null;

}

So here’s the real point of this tutorial…how do we match the screen coordinates that the user clicks to the latitude & longitude of our icon on the map?

Just as we determined the location of our map for drawing on the screen, we will now create a Rectangle to represent that drawn icon and use the Rectangle.contains() method to test whether the user’s MotionEvent occurred within that Rectangle.

private MapLocation getHitMapLocation(MapView mapView, MotionEvent    event) {

// Track which MapLocation was hit…if any
MapLocation hitMapLocation = null;

RectF hitTestRecr = new RectF();
int[] screenCoords = new int[2];
Iterator<MapLocation> iterator = mapView.getMapLocations().iterator();
while(iterator.hasNext()) {

MapLocation testLocation = iterator.next();

// As above, translate MapLocation lat/long to screen coordinates
mapView.getProjection().getPointXY(testLocation.getPoint(), screenCoords);

// Use this information to create a ‘hit” testing Rectangle to represent the size
// of our location’s icon at the correct location on the screen.

// As we want the base of our balloon icon to be at the exact location of
//
our map location, we set our Rectangle’s location so the bottom-middle of
//
our icon is at the screen coordinates of our map location (shown above).
hitTestRecr.set(-bubbleIcon.width()/2,-bubbleIcon.height(),bubbleIcon.width()/2,0);

// Next, offset the Rectangle to location of our location’s icon on the screen.
hitTestRecr.offset(screenCoords[0],screenCoords[1]);

// Finally test for match between ‘hit’ Rectangle and location clicked by the user.
// If a hit occurred, then we stop processing and return the result;

if (hitTestRecr.contains(event.getX(),event.getY()) {

hitMapLocation = testLocation;
break;

}

}

return hitMapLocation;

}

And that’s it for hit testing. If a hit occurred in our Rectangle, we track the selected map location and render a popup window above the map location’s icon with the name of the location.

Drawing a Popup Information Window

The following code for displaying a popup window may look complex, but the goal is simple – to set the correct screen coordinates for the information window to display directly above & centered on our location’s icon.

private void drawInfoWindow(Canvas canvas, MapView mapView, boolean shadow) {

// Again get our screen coordinate
int[] selDestinationOffset = new int[2];
mapView.getProjection().getPointXY(selectedMapLocation.getPoint(), selDestinationOffset);

// Setup the info window with the right size & location
int INFO_WINDOW_WIDTH = 125;
int INFO_WINDOW_HEIGHT = 25;
RectF infoWindowRect = new RectF(0,0,INFO_WINDOW_WIDTH,INFO_WINDOW_HEIGHT);
int infoWindowOffsetX = selDestinationOffset[0]-INFO_WINDOW_WIDTH/2;
int infoWindowOffsetY = selDestinationOffset[1]-INFO_WINDOW_HEIGHT-bubbleIcon.height();
infoWindowRect.offset(infoWindowOffsetX,infoWindowOffsetY);

// Draw inner info window
canvas.drawRoundRect(infoWindowRect, 5, 5, getInnerPaint());

// Draw border for info window
canvas.drawRoundRect(infoWindowRect, 5, 5, getBorderPaint());

// Draw the MapLocation’s name
int TEXT_OFFSET_X = 10;
int TEXT_OFFSET_Y = 15;
canvas.drawText(selectedMapLocation.getName(),infoWindowOffsetX+TEXT_OFFSET_X,infoWindowOffsetY+TEXT_OFFSET_Y,getTextPaint());

}

And that’s it. Please let me know of any points that need clarification or that I should expand/improve upon.

Here is the .apk you can use along with the source files: tutorial2.zip.

Happy coding,

Anthony (Acopernicus)

22 Responses to “Android Tutorial 2: “Hit” testing on a View (MapView)”


  1. 1 adrian April 9, 2008 at 1:23 pm

    great tutorial, thanks!

  2. 2 Chris August 22, 2008 at 12:11 pm

    Any chance you could update this with the current SDK? PixelCalculator doesn’t seem to exist anymore. What is the correct API’s?

    Thanks.

  3. 3 Brijesh Patel September 25, 2008 at 12:46 pm

    Can you let us know, what changes would be required to upgrade this code to SDK-1.0 .

  4. 4 Biosopher September 26, 2008 at 7:45 pm

    I’ll try to update the tutorials once soon but will probably be another couple weeks.

    The primary change is that PixelCalculator is no longer present. It has been renamed to Projection and is accessed from MapView.getProjection().

    Let me know if that change solves your problem.

    Anthony

  5. 5 Cassiano Tartari November 12, 2008 at 5:31 am

    The code of tutorial2.zip attach on this page is not compatible with the code of the site. In the site SDK1.0 in attach SDK m5-r15

  6. 6 AndroidMani February 20, 2009 at 1:52 am

    how about displaying a button? Like to search nearby, or show a menu specific to the placeholder?

  7. 7 Biosopher February 20, 2009 at 9:48 am

    We’ll be updating this tutorial sometime…probably not very soon though. :-(

    For displaying buttons or menus, the best choice is to simply popup an XML-defined layout when the users clicks the appropriate location. See tutorial #1.

    Anthony

  8. 8 hggcrazy March 31, 2009 at 7:24 pm

    great thank you!

  9. 9 dedachi April 2, 2009 at 9:27 am

    I want to integrate a Chat Application on the markers for particular
    locations on Google Maps.

    Eg: If I am going to visit location x, and I have located it on Google
    Maps.
    Now upon clicking on the marker, I should be able to pop up a chat application which can enable me to chat with friends. Is this possible ? Please suggest

  10. 10 adnroidUser April 12, 2009 at 10:03 am

    I had seen your example to display the bubble in the google map.

    Without using tutorial2.xml, its possible to call the MapLocationViewer inside the class such that

    //setContentView(R.layout.tutorial2); //To avoid

    alternatively I planned to call
    setContentView((View)new MapLocationViewer(????));

    Question:
    1) How to get the context of the current activty to pass in setContentView((View)new MapLocationViewer(????));
    2) How to get a view from resource id

  11. 11 happyhan April 15, 2009 at 5:29 pm

    Dear Anthony,
    I have a trouble with mapview overlay. I want to receive
    a sms which contains latitude and longitude,then I hope to draw a icon on mapview according to these location info. Now I have received a sms and parsed it,then transfer it to mapview. but the overlay is not implemented. So would you give me some advice ?

    Best Regards

    happyhan

  12. 12 xxJyen May 23, 2009 at 1:07 am

    hi, Anthony.

    how do i combine tutorial2 and tutorial5 together?
    (when hit on the map, show the transparentPanel)

    sorry for the pool English :(

  13. 13 Biosopher May 23, 2009 at 9:22 am

    Hi xxJyen,

    Just display the panel when the user touches the screen. I.e. listen for the onTouchEvent and then display the popup.

    Anthony

    • 14 xxJyen May 24, 2009 at 8:09 am

      hello!

      i want users click the specific location on map and pop it’s information(transparentPanel).

      i have tried to modify LocationOverlay and LocationViewer, but i cant get the instance of popup, location_name..etc

      becuz the findViewByid method doesnt work in OverLay.
      how could I solve this problem

  14. 15 Biosopher May 24, 2009 at 10:24 am

    Hi xxJyen,

    You should reread the two tutorials as all the information is in there. You don’t need to do anything special with LocationOverlay and LocationViewer other than what’s in the tutorial. Not sure why you would need the findViewByid method in OverLay.

    Anthony

  15. 16 xxJyen May 24, 2009 at 8:00 pm

    hi, Anthony.

    i read the two tutorials again.

    tutorial2 teaches me how to draw on the canvas directly when user clicks the overlayitems.

    tutorial5 teaches me how to show an anime when user clicks the button.

    is that right?

    i want to modify the tutorial2. when users clicks the overlayitems, show the info by pop a transparency panel instead of drawing on the canvas.

    so first i create a layout like this

    // id:xx

    second, i try to change the method of displaying info.
    in the MapLocationOverlay void draw(Canvas, MapView, Boolean)

    // drawMapLocations(canvas, mapView, shadow)
    // drawInfoWindow (canvas, mapView, shadow)
    // i try to display some infomation just like tutorail5, so..

    TransparentPanel popup= (TransparentPanel)findViewById(R.id.xx);


    popup.setVisibility(View.VISIBLE);
    popup.startAnimation( animShow );
    showButton.setEnabled(false);
    hideButton.setEnabled(true);

    but the code cant pass the compile :(

    xxJyen

    • 17 xxJyen May 24, 2009 at 8:04 pm

      layout

      - com.pocketjourney.view.mapLocationviewer
      - com.pocketjourney.view.TransparentPanel //id:xx
      — Button
      — ImageView
      — TextView

  16. 18 Ben Tseng June 5, 2009 at 6:56 pm

    Thank you very huge!!
    I tried to display information windows by onTap()
    However,I always failed to remove other windows.

    Thanks again.


  1. 1 Android Tutorial #4: Image & Text-Only Buttons « Pocket Journey Trackback on May 2, 2008 at 11:33 am
  2. 2 Android Tutorial #4.2: Passing custom variables via XML resource files « Pocket Journey Trackback on May 2, 2008 at 12:12 pm
  3. 3 Tutorial 1: Transparent Panel (Linear Layout) On MapView (Google Map) « Pocket Journey Trackback on June 30, 2008 at 7:19 am
  4. 4 Android Tutorial 3: Custom Media Streaming with MediaPlayer « Pocket Journey Trackback on December 23, 2008 at 9:43 am

Leave a Reply




a