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:
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.
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.